- Home /
Why is my rigidbody.velocity not working?
Hi Unity devs,
I am having a GameObject with a sprite script added to it. I have attached a boxcollider and a rigidbody as well to that object and I am trying to execute this:
void Update() {
float jumpspeed = 8.0f;
if (Input.GetKeyDown (KeyCode.Space))
{
rigidbody.velocity += jumpspeed * Vector3.up;
}
}
This script is attached to the current gameobject.
Here nothing seems to be happening when I press spacebar.
Why is that so?
I'm not an expert coder so I can't say why this isn't working exactly but I think you are trying to add a velocity to your rigid body ins$$anonymous$$d of force.Think of it this way.You can't move any object in real life by simply adding velocity to it.Physics doesn't work that way.In order to have velocity you must give the object a push or have a force acting on it.Like giving a ball a kick.You add a force to the ball by kicking which then causes the ball to move with a certain velocity. I'd say try to add this ins$$anonymous$$d inside your if statement rigidbody.AddForce(0,jumpSpeed,0);
. This will simply add a force to your object along the y axis.You will need to add some logic to prevent the player from jumping mid air or multiple times in a row though. Also try changing jumpspeed
to jumpSpeed
.It's a small change but allows for an easier read of the code for everyone :)
Answer by diogomota · Jul 08, 2013 at 10:55 AM
that code is working fine here, maybe you are using a different up vector.. try with other vector3 directions.