- Home /
rigidbody.Velocity stops gravity
Hello!
i have this script that moves the player (rigidbody with gravity) and makes it jump when "Space" is pressed.
The problem is that if I press W,A,S or D while on air, it stops falling and walks in middle-air. It fells only when I release the movement button. Any help?
if (Input.GetKey(KeyCode.W))
{
animation.CrossFade("walk");
rigidbody.velocity = transform.forward * speed;
}
if (Input.GetKey(KeyCode.S))
{
animation.CrossFade("walkBack");
rigidbody.velocity = transform.forward * -speed;
}
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(0,-rotationSpeed,0);
animation.CrossFade("strafeL");
}
if(Input.GetKey(KeyCode.D))
{
transform.Rotate(0,rotationSpeed,0);
animation.CrossFade("strafeR");
}
if(Input.anyKey == false)
{
animation.CrossFade("idle");
}
// Jumping and attacking
if (Input.GetButtonDown ("Jump") && foot.grounded == true)
{
animation.Play("jump");
rigidbody.AddForce(0,300,0);
}
Comment
Best Answer
Answer by robertbu · Jun 20, 2013 at 06:34 PM
To solve this, construct a vector using the current 'y' velocity:
if (Input.GetKey(KeyCode.W))
{
animation.CrossFade("walk");
var v3 = transform.forward * speed;
v3.y = rigidbody.velocity.y;
rigidbody.velocity = v3;
}
Answer by Stalex150 · Jan 25, 2018 at 02:42 PM
Work for me :
rb.velocity = new Vector2(speed , rb.velocity.y);