I am making a game in Unity where you move around with WASD and space to jump. This is my code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public bool canJump;
void FixedUpdate () {
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, 750 * Time.deltaTime, ForceMode.Acceleration);
}
if (Input.GetKey("a"))
{
rb.AddForce(-750 * Time.deltaTime, 0, 0, ForceMode.Acceleration);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, -750 * Time.deltaTime, ForceMode.Acceleration);
}
if (Input.GetKey("d"))
{
rb.AddForce(750 * Time.deltaTime, 0, 0, ForceMode.Acceleration);
}
if (canJump)
{
if (Input.GetKeyDown("space"))
{
rb.AddForce(0, 10, 0, ForceMode.VelocityChange);
Debug.Log("jump");
canJump = false;
}
}
Vector3 v = rb.velocity;
v.y = 0;
v = Vector3.ClampMagnitude(v, 6);
v.y = rb.velocity.y;
rb.velocity = v;
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.name == "Ground")
{
canJump = true;
}
}
void OnCollisionExit(Collision other)
{
if (other.gameObject.name == "Ground")
{
canJump = false;
}
}
}
But, when I jump, it sometimes goes quite high, and sometimes barely jumps at all. I have tested whether holding down the space bar makes any difference, and it doesn't. I have tried using ForceMode.Impulse and ForceMode.VelocityChange, but the jumping is still inconsistent.
I have also noticed that the player only jumps high up in the air when its Y value on the floor is around ~0.23. It can also be ~0.16, like this, and it doesn't jump very high at all.
This is ~0.16
And this is ~0.23

The lowest jump takes it up to a Y value of ~0.7, but the highest jump takes it up to around 4.83.
If anyone has any ideas, I'd be very grateful.