My Check ground function in Unity3D dosen't Work - c#

I've made a small game, since I am a beginner in Unity and I wanted to add a boolean colider to see if my spinning ball was on the ground for it to jup, but it dosen't work.
Thank you ! Here is the code :
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class script_mouvement : MonoBehaviour
{
Rigidbody rb;
[SerializeField] float movementSpeed = 6f;
[SerializeField] float jumpForce = 5f;
[SerializeField] Transform groundCheck;
[SerializeField] LayerMask ground;
[SerializeField] AudioSource jumpSound;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
rb.velocity = new Vector3(horizontalInput * movementSpeed, rb.velocity.y, verticalInput * movementSpeed);
if (Input.GetButtonDown("Jump")&& isGrounded())
{
Jump();
}
}
void Jump()
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
}
bool isGrounded(){
Collider[] colliders = Physics.OverlapSphere(groundCheck.position, 1.0f, ground);
for (int i = 0; i < colliders.Length; i++) {
if (colliders[i].gameObject != gameObject) {
return true;
}
}
return false;
}
}`
I tried to add a collision check but it didn't work , I expected the ball to jup when It was on the ground

Related

Unity 2D Character Vibrates When Touching Wall

Like the title says when i walk into a wall i start to vibrate. It doesn't affect gameplay just graphics i believe. The game is a 2D platformer using rigidbody 2D. I am new to game dev so what you fixed could you please tell me how you fix it. Thank you.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float MovementSpeed = 1;
public float JumpForce = 1;
private Rigidbody2D _rigidbody;
private float coyoteTime = 0.2f;
private float coyoteTimeCounter;
private float jumpBufferTime = 0.05f;
private float jumpBufferCounter;
[SerializeField] private Rigidbody2D rigidbody2D;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
private bool isGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (isGrounded())
{
coyoteTimeCounter = coyoteTime;
}
else
{
coyoteTimeCounter -= Time.deltaTime;
}
if (Input.GetButtonDown("Jump"))
{
jumpBufferCounter = jumpBufferTime;
}
else
{
jumpBufferCounter -= Time.deltaTime;
}
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
if (coyoteTimeCounter > 0f && jumpBufferCounter > 0f)
{
_rigidbody.velocity = new Vector2(_rigidbody.velocity.x, JumpForce);
jumpBufferCounter = 0f;
}
if (Input.GetButtonUp("Jump") && _rigidbody.velocity.y > 0f)
{
_rigidbody.velocity = new Vector2(_rigidbody.velocity.x, _rigidbody.velocity.y * 0.5f);
coyoteTimeCounter = 0f;
}
}
}
Sorry if the code is sort of sloppy. I am using multiple tutorials to make the movement perfect for me.
Ah! I have had this problem before.
The reason the vibration is happening, is because you are adding a force manually through rigidbody.velocity. The better (And more efficient) way to do it is through rigidbody.AddForce(). This should allow for the rigidbody to calculate physics much smoother.
The only issue that may arise is if you plan for the player to have a constant speed. If you AddForce(1000) with no other arguments, the character will start accelerating, instead of moving at a constant speed.
If you need the player to move at a constant speed, you can append a ForceMode to! I am not sure what one you would use, but that my idea. One example would be rigidbody.AddForce(1000, ForceMode.VelocityChange),

C# Unity Animation

There was a problem with Unity animations. When the character jumps, the animation is played, but if the character jumps in either direction, the animation does not stop and the character with this animation rolls on the ground.
https://ibb.co/hLKmK6W
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovent : MonoBehaviour
{
public GameObject player;
public float speed = 10f;
private Rigidbody2D rb;
public int jump = 350 ;
Animator animation;
private bool inground;
// Start is called before the first frame update
void Start()
{
animation = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
var moveX = Input.GetAxis("Horizontal");
if (Input.GetKey(KeyCode.Space) && rb.velocity.y == 0)
{
rb.AddForce(Vector2.up * jump);
animation.SetTrigger("Jump");
}
rb.velocity = new Vector2(moveX * speed, rb.velocity.y);
if (animation)
{
animation.SetBool("Run", Mathf.Abs(moveX) >= 0.1f);
}
Vector3 charecterScale = transform.localScale;
if (Input.GetAxis("Horizontal") < 0)
{
charecterScale.x = -7.215315f;
}
if (Input.GetAxis("Horizontal") > 0)
{
charecterScale.x = 7.215315f;
}
transform.localScale = charecterScale;
}
}
You need to check if you are grounded or not. there is an example in this video:
https://youtu.be/CSu7MWv8qEY
The solution to this would be to check if the player is grounded, using Physics2D.Raycast() or Physics2D.OverlapCircle() and passing it as a boolean to the animator, like this:
public float radius = .5f;
public Vector2 offset = new Vector2(0, -.5f, 0);
public LayerMask layermask;
Animator animation;
Rigidbody2D rb;
void Start()
{
animation = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
bool IsGrounded() => Physics2D.OverlapCircle((Vector2)transform.position + offset, radius, layermask);
// to visualize the circle
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position + (Vector3)offset, radius);
}
void FixedUpdate()
{
animation.SetBool("isGrounded", IsGrounded());
}

How to make my 2D character 'look' or flip in the direction he is moving?

I'm a total newbie in Unity and I'm learning/making my first game, which will be a platformer. I want to get the movement perfect first. I've added a simple script that enables the player to move and jump.
Here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour{
public float jumpspeed = 5f;
public float speed = 5f;
Rigidbody2D rb;
GameObject character;
// Start is called before the first frame update
void Start()
{
}
void Awake(){
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)){
Jump();
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += move *Time.deltaTime * speed;
}
void Jump(){
rb.AddForce(new Vector2(0f, jumpspeed), ForceMode2D.Impulse);
}
}
Now, I want the character to face in the direction in which it moves. The png is facing to the right by default.
How can I do that? Also, can I make my movement script better?
Thanks in advance!
I typically do this using code like this based off a bool.
void FlipSprite()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

With what I should replace dirX for my bullets to shoot right and left

I am doing a 2d game and I want to know how I can make the bullets to shoot right and left . At this moment the bullets go just to the left , even if my player moves right. How I can make them shoot both sides or shoot just when they find an object tagged " enemy "
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Character : MonoBehaviour
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
You're already accounting for the direction of the barrel. You just need to change the direction of the barrel when you move.
One way to do that is to just set that directly:
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX !=0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
If the barrel is a child of the player object, then changing the character's rotation so that the barrel's direction points in the correct direction will also work. There's not enough information in the question to know for sure but maybe using Quaternion.LookRotation to set the character's rotation like so would work:
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX !=0)
{
Vector3 newPlayerForward = Vector3.forward * Mathf.Sign(dirX);
transform.rotation = Quaternion.LookRotation(newPlayerForward, Vector3.up);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}

Trying to create a 3rd person controller in Unity but the player is not moving

This is what I have so far.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
CharacterController control;
[SerializeField]
float moveSpeed = 5.0f;
[SerializeField]
float jumpSpeed = 20.0f;
[SerializeField]
float gravity = 1.0f;
float yVelocity = 0.0f;
// Use this for initialization
void Start () {
control = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update ()
{
Vector3 direction = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
Vector3 velocity = direction * moveSpeed;
if (control.isGrounded) {
if (Input.GetButtonDown ("Jump")) {
yVelocity += jumpSpeed;
}
} else {
yVelocity -= gravity;
}
velocity.y = yVelocity;
control.Move (velocity*Time.deltaTime);
}
}
I'm following a tutorial, and it looks like everything is the same, but the player is not moving.
If it is all same with tutorial, your problem must be about your input settings. Check your "Horizontal", "Vertical", "Jump" from Edit -> Project Settings -> Input
Then on inspector look at variables under Axis list to check them if they assigned true, maybe there is no Horizontal or Vertical variable.

Categories