- Home /
Velocity for movement
I am working on a character movement script that uses rigidbody.velocity for player movement. only problem is with the current script if i am running and try to jump it doesnt work properly i believe i know why but i am unsure of how to fix it.
void FixedUpdate ()
{
if (Input.GetKey(KeyCode.D) && isGrounded == true)
{
rigidbody.velocity = new Vector3(movementForce, 0, 0);
//rigidbody.AddForce(Vector3.right * movementForce * Time.deltaTime * 100);
}
if (Input.GetKey(KeyCode.A) && isGrounded == true)
{
rigidbody.velocity = new Vector3(-movementForce, 0, 0);
//rigidbody.AddForce(Vector3.right * -movementForce * Time.deltaTime * 100);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
//rigidbody.velocity += new Vector3(0, jumpForce, 0);
rigidbody.AddForce(Vector3.up * jumpForce * 100);
}
}
with the rigidbody.velocity since i am setting the value directly i believe it causes any other changes to bug out. i can change it to
rigidbody.velocity += new Vector3(movementForce, 0, 0);
but when i move it constantly speeds up the longer the key is held. if i can get a way to limit the velocity to not exceed a certain speed then it would fix it. only problem is i don't know how =(.
You shouldn't change rigidbody.velocity directly. And before you ask,
rigidbody.velocity += new Vector3(movementForce, 0, 0);
still counts as changing it directly. You should use Rigidbody.AddForce along with sane values for drag and friction. I usually do something along the lines of making the drag inversely proportional to the current user input- so if the player isn't moving, the drag is really high (so that the character doesn't slide everywyere), and if the player wants to go somewhere, the drag goes down again.
Also, use Input.GetAxis. It's much cleaner for what you're trying to do (and allows you to get 360 degree turns!)
Took me a bit to figure it out but what i came up with is this :
if (rigidbody.velocity.x >= 10) { rigidbody.velocity = new Vector3(10, yInt); }
so every time the movement key is held it will check to see what the velocity is. and if it exceeds what i want it will lock it there until the key is released =D