- Home /
Constrain Total Number of Jumps
Hi,
I am curious how you can limit the total number of jumps in a game. I currently only want one jump, but later might implement a double jump. More to the point I would like to base jumping on collisions. That is to say, if the hero jumps and hits a wall, the jumpCounter should reset back to zero allowing the hero to start jumping again.
Here is a snippet:
var isFalling : boolean=true;
function Update () {
var fingerCount = 0;
for (var touch : Touch in Input.touches) {
if (touch.phase == TouchPhase.Began)
fingerCount ++;
}
if (fingerCount > 0)
rigidbody.velocity.y=7;
}
function OnCollisionStay(collisionInfo : Collision) {
isFalling=false;
}
Thank you
Answer by aldonaletto · Apr 20, 2012 at 01:37 AM
I would have a jumping flag: only jump when it's false and nJump < maxJumps. When jumping, set the jumping flag. In OnCollisionStay, clear jumping and count the jump only when was jumping and landed on the ground:
var jumping = true; var maxJumps = 1; var nJump = 0;
function Update () { var fingerCount = 0; for (var touch : Touch in Input.touches) { if (touch.phase == TouchPhase.Began) fingerCount ++; } // only jumps if not jumping yet and if maxJumps not exceeded if (fingerCount > 0 && !jumping && nJump < maxJumps){ rigidbody.velocity.y = 7; jumping = true; // is jumping now } }
function OnCollisionStay(collisionInfo : Collision) { // if was jumping and landed in some Ground object... if (jumping && collisionInfo.gameObject.CompareTag("Ground")){ jumping = false; // jump ended nJump++; // count the jump } }
I'll try this out when I get home, but doesn't there need to be some sort of touchCount restriction like:
touchCount < 2; since every touch triggers a jump?
I don't know much about touches, but it seems that touchCount only tells how many fingers are touching the screen. In the script above, touches are ignored when jumping is true. When you do the first touch, the character is allowed to jump because jumping is false. This sets jumping to true, and it's only reset to false when the character lands on some Ground tagged object - and then the jump is counted, thus no more jumps will occur until the counter is zeroed.
That all makes sense. I will be home soon to take a look. I just was curious what this means in javascript:
!jumping I know what == and != means etc, but just curious how !jumping is being used...
As always, thank you for the assistance.
!jumping means not jumping, or jumping == false. The ! operator is the logical NOT, and works in javascript, C#, Boo - basically all languages created after the old and good C
Your answer
Follow this Question
Related Questions
Moving forward whilst jumping 3 Answers
Physics on a Ball 1 Answer
Make a character jump when user taps the screen of an android device 1 Answer
How To Create Android 3d Game Jump Button 2 Answers
Jumping irregularities 1 Answer