Reputation: 39
So, the player can jump using the Spacebar key and has a gravity pulling him towards the floor. What I want is that, if he is not on the floor anymore, you cannot press jump again, till you've fall. I tried making a boolean and implementing it the movement, but still no results. Any idea how I could do it?
var keyPressed:int = -1;
player.addEventListener(Event.ENTER_FRAME, iMoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, iSetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, iUnsetKeyPressed);
function iSetKeyPressed(event:KeyboardEvent):void
{
if (canJump == true) {
keyPressed = event.keyCode;
} else if (canJump == false) {
keyPressed = -1;
}
}
function iUnsetKeyPressed(event:KeyboardEvent):void
{
keyPressed = -1;
}
function iMoveInDirectionOfKey(event:Event)
{
player.y += keyPressed == Keyboard.SPACE ? -20 : 0;
}
var gravity:Number = 15;
var floor:Number = stage.stageHeight - player.height / 2 + 35;
var canJump:Boolean = true;
iCanJump(canJump);
player.y = floor;
player.addEventListener(Event.ENTER_FRAME, iGravity);
function iGravity(pEvent)
{
if (keyPressed != Keyboard.SPACE) {
player.y += gravity;
}
if (player.y > floor) {
player.y = floor;
}
}
function iCanJump (canJump:Boolean) {
if (player.y == floor) {
canJump = true;
}
if (player.y < floor) {
canJump = false;
}
}
Upvotes: 1
Views: 191
Reputation: 7962
Use a speed variable like this:
public var jumpSpeed : Number = -20;
public var ySpeed : Number = 0;
public var gravity : Number = 1;
function iSetKeyPressed(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.SPACE && player.y == floor)
ySpeed = jumpSpeed;
}
player.addEventListener(Event.ENTER_FRAME, iGravity);
function iGravity(e : Event)
{
player.y += ySpeed;
if(player.y < floor)
{
ySpeed += gravity;
}
else
{
ySpeed = 0;
player.y = floor;
}
}
You basically create a speed variable for the player and update it each turn. You update the player position on y-axis by the player speed as well.
You can even check the time between frames and multiply the speed by the time to get a smooth result if you continue working on this.
Good luck.
Upvotes: 1