- Home /
Why is it so hard to make a rigidbody jump in the unity engine?
I frequently start Unity projects as a hobbyist and just like to fiddle around. Every time I make a game, 2D or 3D, I find the jump mechanic to be impossibly hard to program.
Currently I'm trying to make a 3D rigidbody jump, but it INSTANTLY reaches height and then slowly falls (doesn't even accelerate under gravity)... see the gif below. EDIT** Can't seem to upload an image in this forum anymore... see link below.
I've tried using transform.Translate... directly setting rigidbody.velocity... doing rb.AddForce with different forcemodes and everything (except the translate function, but I don't want to use this) causes the same thing to happen. I've had this problem every time I make a game and can never figure it out.
I find it a bit ridiculous that over the course of 3 years of me making games there still is no easy fix for this in this engine... does anyone know what is causing this? Code and image below
void Update()
{
//Movement input
float strafe = Input.GetAxis("Horizontal");
float movement = Input.GetAxis("Vertical");
playerRigidbody.velocity = (transform.forward * movement + transform.right * strafe).normalized * movementSpeed;
//Rotation
if (Input.GetMouseButton(1))
{
float h = mouseSensitivity * Input.GetAxis("Mouse X");
transform.Rotate(0, h, 0);
}
//Jump
if (Input.GetKeyDown(KeyCode.Space) && GroundCheck())
{
playerRigidbody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
Answer by Buckslice · Dec 21, 2017 at 09:43 PM
When you set the velocity directly each frame you are overriding and forgetting about the y velocity, which removes the acceleration from gravity and makes the upward jump force only lasts one frame. Replace the code on line 8 with this.
float yVel = playerRigidbody.velocity.y;
Vector3 newVel = transform.forward * movement + transform.right * strafe;
newVel = newVel.normalized * movementSpeed;
newVel.y = yVel;
playerRigidbody.velocity = newVel;
Thank you sir, you are wonderful. Added some gravity and it works nicely now.