Reputation: 2551
This is my JSFiddle: http://jsfiddle.net/Au6br/13/
The problem is when I keep pressing keydown.up
the player jump multiple times. What I want is to define a variable called JumpCount
so when the player jump if the jump variable is greater than this value the jumping stop.
Character.prototype.Jump = function () { // Jumping
character.MaxJump += gravity;
character.y += character.MaxJump;
if (keydown.up) {
if (!character.jumping) {
character.jumping = true;
character.Pos = 4;
character.Row = 2;
character.h = 23;
character.MaxJump = -character.sp * 2.5;
}
}
if (character.y >= ch - character.h) { // if the character is under the bottom
character.y = ch - character.h;
character.jumping = false;
}
};
Upvotes: 5
Views: 359
Reputation:
I'd do it like this:
Character.prototype.Jump = function () {
character.MaxJump += gravity;
character.y += character.MaxJump;
if (keydown.up) {
if (character.CurrentJumps < character.JumpCount) {
character.CurrentJumps++
character.Pos = 4;
character.Row = 2;
character.h = 23;
character.MaxJump = -character.sp * 2.5;
}
}
if (character.y >= ch - character.h) {
character.y = ch - character.h;
character.CurrentJumps = 0
}
};
Were JumpCount is the max jumps, and CurrentJumps is the currently done jumps
And an example to set to double jump:
character.JumpCount = 2 // 2 Jumps
Upvotes: 1
Reputation: 4833
The first problem is that you can jump when you're not on the ground. It's because of the Onground
function.
Replace this :
return this.y <= ch - this.h;
With this :
return this.y >= ch - this.h;
You should also use this function in Jump
to avoid duplicate code :
if (character.Onground()) { // if the character is under the bottom
character.y = ch - character.h;
character.jumping = false;
}
Counting the jumps (I assume you want to make double jumps) can't work as long as you test if(keydown.up)
. When you press the UP key, this value will be true for more than one frame (depending on the duration the player presses it), so you'll never be able to correctly count the number of jumps. You must bind the jump on the onkeydown
event, which is called once. After that, it will be simple to replace character.jumping with an integer.
Upvotes: 1
Reputation: 1009
How about you add a variable called jumpCount
or something that you increase every time the character jumps. Only allow the character to jump if jumpCount
is smaller or equal to the number of jumps you like the character to be able to do. Then just set jumpCount
to zero when the player touches the floor. This also gets rid of your jumping
variable since this would mean the same thing as jumpCount === 0
.
Upvotes: -1