Skip to main content

Jumping using a Rigidbody

Below is a complete movement and jump script for using the New Input System with a Jump action added.

Import the New InputSystem using the package manager.

Add the Player Input component to the player

Create default inputs and assign to the player input component

Open the Input Actions

Click + in Actions to add a new action

Name the action, in this case Jump.

You can then use a function OnJump in the scripts.

Whatever you call the action will be the name of the function with On in front of it for the scripts. e.g. Action of Duck would have a function OnDuck

Lines 14-15> Variables to check if the player has pressed the jump key and a variable for checking if the player is grounded on the floor and can therefore jump.

Lines 31-55 > Handle the jump input on OnJump() and then the collusion detectors check if the player has jumped off of the floor. Note that the objects have a floor tag assigned to them. When a player exits a collider the player has jumped when they enter it they have landed.

Lines 66-71 > Code for the fixed update to check if the jump is pressed and on the ground and then apply the force to move the player.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class RollABallPlayer : MonoBehaviour
{
public float speed = 5;
public float jumpSpeed = 10;

private Rigidbody rb;
private float movementX;
private float movementY;
private bool jump = false;
private bool isGrounded = false;

// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}

private void OnMove(InputValue input)
{
Vector2 movement = input.Get<Vector2>();

movementX = movement.x;
movementY = movement.y;
}

private void OnJump()
{
if (isGrounded == true)
{
Debug.Log("Jumping");
jump = true;
}
}

private void OnCollisionEnter(Collision theCollision)
{
if (theCollision.gameObject.tag == "Floor")
{
isGrounded = true;
}
}

//consider when character is jumping .. it will exit collision.
private void OnCollisionExit(Collision theCollision)
{
if (theCollision.gameObject.tag == "Floor")
{
isGrounded = false;
}
}

// Update is called once per frame
void FixedUpdate()
{
//rb.transform.Translate(new Vector3(0.0f, 0.0f, movementY));
//rb.transform.Rotate(new Vector3(0.0f, movementX, 0.0f));

rb.AddTorque(Vector3.forward * -1 * movementX * speed);
rb.AddForce(Vector3.forward * movementY * speed);

if (jump == true && isGrounded == true)
{
Debug.Log("Here");
rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
jump = false;
}
}
}