- Home /
Setting time of the jump
I have this simple script that makes player jump when he starts pressing space.
For now player can jump for a certain height, the problem is as height gets longer, jump time also gets longer and that's not what I want, I want to make that time constant, no matter what height of jump is and no matter how strong gravity force is.
There is a trick to decrease jump time by increasing gravity when player has jumped, but that makes more problems then solutions, jump height will be shorter and I don't know how much should I increase gravity force to make the time of the jump to be a value determined by jumpTime.
Here's the code (part of it):
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 1.0f;
public float jumpHeight = 1.5f;
public float jumpTime = 1f;
public float gravity = 10f;
Vector3 InputAxis = Vector3.zero;
Rigidbody rig;
//First frame
void Start() {
//Init rig
rig = GetComponent<Rigidbody>();
//Disable Physics.gravity on this object
rig.useGravity = false;
}
//void Update() {...} //sets the inputAxis value
//Physics frame
void FixedUpdate() {
//Initialize velocity change vector
Vector3 velocityChange = Vector3.zero;
//Calculate jump velocity
//InputAxis.y is only 1.0 when space is pressed down (GetKeyDown), otherwise it's 0.0
velocityChange.y = Mathf.Sqrt(InputAxis.y * jumpHeight * 2 * gravity);
//Add velocity change
rig.AddForce(velocityChange, ForceMode.VelocityChange);
//Add gravity force
if(velocityChange.y > 0) //If player has jumped
rig.AddForce(0, -gravity * jumpTime, 0, ForceMode.Acceleration); //not working...
else
rig.AddForce(0, -gravity, 0, ForceMode.Acceleration);
//Reset input axis
InputAxis.Set(0, 0, 0);
}
}
Answer by ado112 · Aug 06, 2016 at 05:12 PM
After spending some time on wiki reading about uniformly accelerated motion, I found this nice formula for calculating gravity: a = (2 * s) / ( t ^ 2)
So in my case: a is gravity, s is jump height and t is jump time divided by 2.
By calculating velocity (v = sqrt(2 a s)) and passing it to addForce (ForceMode.VelocityChange) every time the space key is pressed down.
Using that I get quite precise results ( +- around 5% ) for jump time.
It could be more precise if I decrease fixed timestep ( bad idea ) and class that I created for counting time is totally dependent on Time.timeSinceLevelLoad (float) so perhaps that floating point precision may be a little issue in some cases.
And its important to note that the gravity calculated by this formula must be in that last AddForce (ForceMode.Acceleration) function.