Home > OS >  Rigidbody2D: How do I prevent the Y axis from being overwritten with 0?
Rigidbody2D: How do I prevent the Y axis from being overwritten with 0?

Time:10-21

public void MoveCharacter(float directionHori) //either -1 or 1
{      
    direction = new Vector2 (directionHori, 0); //new vector2 using passed x value (1 or -1). //BUG - passing in 0 as Y axis overrides gravity while player is moving.

    rb.MovePosition(rb.position   direction * moveSpeed * Time.fixedDeltaTime); //apply movement 
}

Above is my MoveCharacter method, and when it is called, the Y axis is overwritten with 0 therefore gravity is disabled, allowing the player to fly when he's supposed to fall. This is a 2D sidescroller, therefore the player should not be able to move vertically (except when falling of course). I've tried direction = new Vector2 (directionHori, rb.Velocity.y); //replacing 0 with rb.Velocity

however that creates weirder behavior. Any help would be appreciated, I'm still new to Unity! Many thanks.

CodePudding user response:

Instead of using MovePosition where you would need to calculate the final position yourself you could rather simply adjust the velocity like

var velocity = rb.velocity;
velocity.x = direction * moveSpeed;
rb.velocity = velocity;

this keeps the gravity and vertical movement untouched and the Rigidbody2D / the physics engine does the calculation for you ;)

CodePudding user response:

Relating to derHugo's answer, you want to use rb.velocity (or rb.AddForce()) instead. Also, when moving a rigidbody object it is best to call your move method from FixedUpdate(), because regular Update() is called every frame; Where as FixedUpdate() is called with the physics engine (about every other frame). Since a rigidbody object is a physics object, you could experience weird behaviour when trying to move from regular Update().

  • Related