- Home /
My movement script is kind of broken for jumping (upward force is diminished after first jump)
This script I'm using on a Rigidbody object is KIND OF working. My first jump is pretty high, and all subsequent jumps are about 1/8th the force. What gives?
#pragma strict
var speed : float;
var grounded : boolean = true;
function Update () {
var moveHorizontal : float = Input.GetAxis("Horizontal");
var moveVertical : float = Input.GetAxis("Vertical");
var moveUp : float;
if (Input.GetKeyDown("space") && grounded == true) {
moveUp = 20;
grounded = false;
}
var movement : Vector3 = Vector3(moveHorizontal, moveUp, moveVertical);
rigidbody.AddForce(movement * speed * Time.deltaTime);
}
function OnCollisionStay(collisionInfo : Collision) {
grounded = true;
}
There are a few problems here and confusions.
Functions affecting Forces/Rigidbodies, should be done in FixedUpdate(), not Update().
You make "moveUp = 20" when space is pressed, but I don't see you ever setting it back to 0.
Using OnCollisionStay will cause there to be a bit of a delay before the character is declared grounded. It's better to use OnCollisionEnter.
OnCollisionStay will keep functioning on the frame after you hit jump, so it's going to set you back to grounded as soon as you jump.
What your Inspector while the game is playing, to see how your values are changing when you first try to jump and then after.
So adding var moveUp : float = 0;
and changing Update to FixedUpdate fixes the weird force thing. But now (and before--I failed to mention), I'm allowed a double jump. Grounded isn't unchecked until the second time I press space....
RAD. Thank you. I'd like to mark your comments as an answer. How?
Answer by Invertex · May 08, 2014 at 03:07 AM
Only physics functions should be done in FixedUpdate(), keypresses and other stuff should be done in in Update(). So when Space is pressed in Update(), it will change moveUp to 20, then when FixedUpdate() happens, it will operate based on those new values.
As for the double jump, did you switch to OnCollisionEnter?
Using Raycasts, or OverlapArea below your character, is a more consistent way to check if grounded though, simply disabling the check for a tiny bit after you hit jump. http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.OverlapArea.html