Uneven Jump Heights
I am a beginner and am currently trying to get a sprite to jump up and fall back down. However, I am incapable of getting a consistent jump height.
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed = 20f;
public bool grounded = false;
public float jump = 2.75f;
public float gravity = 9.81f;
Rigidbody2D rb;
public Vector2 vel = new Vector2();
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKeyDown("z") && grounded)
{
vel.y = jump;
}
if (!grounded)
{
vel.y -= gravity * Time.deltaTime;
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + (vel * movementSpeed * Time.deltaTime));
}
}
Note: I do have a trigger which detects the ground and resets both the grounded bool and vel.y. It also triggers the grounded bool again upon exiting said trigger. I have also removed the gravity value on the sprite's rigidbody so that I could have full control.
Any help is much appreciated! Thank you!
Answer by tecses1 · Mar 05, 2020 at 01:04 AM
Use the gravity built into the rigidbody. This can be changed in the project settings, anyway. Next, MovePosition is a interpolated update. Meaning it sets the position over time. This can lead to inconsistencies between the update rate of FixedUpdate and Update. Instead, set the rigidbody velocity directly (in the fixed update) with:
void FixedUpdate()
{
if (Input.GetKey("z") && grounded) //use get key with this boolean.
{
rb.velocity = Vector3.up * 10.0f; //Multiply by strength. 10 could be too much.
}
}
Should fall down with regular physics gravity after that.