Home > Software engineering >  Why does a game object fall slowly when rigidbody2d.velocity.y is equal to 0?
Why does a game object fall slowly when rigidbody2d.velocity.y is equal to 0?

Time:01-26

I'm new to Unity.

rb2.velocity = new Vector2(speed * moveDirection, Y); 

When I set the Y in new Vector() to 0, the character falls slowly because of (I think) the gravity. But when I set the Y to rb2.velocity.y, the character falls ordinarily.

Can you tell me the reason? Thx.

public class SecondCharacterController : MonoBehaviour
{
    public float speed = 1.0f;
    private float moveDirection;

    private Rigidbody2D rb2;
    private Animator anim;

    private void Awake()
    {
        anim = GetComponent<Animator>();  
    }

    private void Start()
    {
        rb2 = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        rb2.velocity = new Vector2(speed * moveDirection, rb2.velocity.y);      // THIS LINE
    }

    private void Update()
    {
        if(Input.GetAxis("Horizontal") != 0)  // Moving
        {
            if(Input.GetKey(KeyCode.A))
            {
                moveDirection = -1.0f;
                anim.SetFloat("speed", speed);
            }
            else if(Input.GetKey(KeyCode.D))
            {
                moveDirection = 1.0f;
                anim.SetFloat("speed", speed);
            }
        }
        else   // Idle
        {
            moveDirection = 0.0f;
            anim.SetFloat("speed", 0.0f);
        }
    }
}

The picture of the scene

CodePudding user response:

private void FixedUpdate()
{
    rb2.velocity = new Vector2(speed * moveDirection, rb2.velocity.y);      // THIS LINE
}

So let's go through the code;

around 60 times per second, or every physics tick, you change the object's velocity (physical direction & speed) to x = speed*direction, y = body's y

Because we're using physics, there is gravity. So when Y is left on its own, it will naturally fall downwards because of gravity, and at first it will fall slowly, but will fall faster due to gravitational acceleration. If you set it to 0, it will restart the gravitational acceleration, starting slow falling, then going faster.

If you set velocity to 0 every update, the character should - theoretically - be floating, however it is possible that the gravitation is applied in between after your 0, so that basically the object will fall in the lowest amount of gravitational acceleration at all times.

velocity.y = body.y

velocity= Doesn't tamper with it and will result in naturally accelerating each update

velocity.y = 0

velocity = Resets the gravitational acceleration, making it 0 or 0 1 gravity each update.

0 doesn't mean "no change", it means "don't move". Setting it to its own y means "no change", or "no tampering", rather.

  •  Tags:  
  • Related