I have tried to implement jumping to my player object, but on hitting the jump key the player object flies into the air extremely quickly, with the Y coordinate infinitely increasing. I have tried changing the jump force but the same thing happens at all values down to a specific point, where the object will not jump at all.
I believe it is something to do with the way I have a max speed implemented for movement, but I can’t figure out exactly how to fix this.
public class PlayerMove : MonoBehaviour
{
public float moveSpeed;
public float maxSpeed;
public float jumpForce;
public float rotationSpeed;
public bool jumpState;
private Rigidbody rBody;
private Vector3 inputVector;
// Start is called before the first frame update
void Start()
{
rBody = GetComponent<Rigidbody>();
jumpState = false;
}
// Update is called once per frame
void Update()
{
inputVector = new Vector3(Input.GetAxis("Horizontal")*moveSpeed, rBody.velocity.y, Input.GetAxis("Vertical")*moveSpeed);
rBody.AddRelativeForce(inputVector, ForceMode.VelocityChange);
if(rBody.velocity.magnitude > maxSpeed)
{
rBody.velocity = rBody.velocity.normalized * maxSpeed;
}
if (Input.GetKeyDown(KeyCode.Space) && !jumpState)
{
rBody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
jumpState = true;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.CompareTag("Ground"))
{
jumpState = false;
}
}
}