This snippet will show you how to make your character to an exact height.
Jumping is in nearly every game. Very often a entire game’s mechanics will revolve around jumping itself.
Here is a quick script on how to make an object in unity jump to a given height. NOTE: Some high school math may be required to understand the concepts, but not to copy and paste the snippet 😀
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerComponent : MonoBehaviour
{
// The height you want the player to jump
public float jumpHeight = 10;
private Rigidbody mRigidbody = null;
// Start is called before the first frame update
void Start()
{
mRigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Maximum Altitude = vertical velocity squared / ( 2 * gravity )
// Maxmium Altitude * 2 * gravity = Vertical velocicty squared
// sqrt ( maximum altitute * 2 * gravity ) = vertical velocity
mRigidbody.AddForce(Vector3.up * Mathf.Sqrt(2 * -Physics.gravity.y * jumpHeight), ForceMode.Impulse);
}
}
}
The magic happens here:
Mathf.Sqrt(2 * -Physics.gravity.y * jumpHeight)
Here is an explanation of where this comes from. The maximum height of a projectile can be calculated as:
hmax=vvert2/2g
In this equation, hmax is the maximum height of the projectile (aka the height we want to jump), vvert is the vertical velocity required to reach that height, and g is the force of gravity.
If we set our player’s vertical (y) velocity to vvert it will reach hmax . We find vvert by simply dividing hmax by 2g, then getting the square root of that value.
hmax=vvert2/2g
hmax (2g)=vvert2
sqrt(hmax (2g))=vvert
These concepts can apply in any game engine, you would just have to adjust the script. The math would remain the same.
I hope this helps. Have fun!
