Warning: rubbish actionscript ahead
i have a bit of a problem with some code I'm working on, which I hope you guys can help me with. It's pretty much the first substantial piece of AS3 I've ever wrote so bear with me here.
I have declared a few variables for directional purposes, gravity and such like so:
var ax:Number = 0;
var ay:Number = 0;
var vx:Number = 0;
var vy:Number = 0;
var gravity:Number = 0.15;
var friction:Number = 0.9;
var jump:Boolean = false;
I have an enter frame function that, as of now, does little else than calling the function for character movement:
function gameLoop(event:Event) {
characterMovement();
}
The characterMovement function looks like this:
function characterMovement():void {
if (inAir() == true) {
friction = 0.99;
}
else {friction = 0.9;}
if (jump == true) {
ay = -20;
jump = false;
}
else {ay = 0;}
vx += ax;
vy += ay;
vy += gravity;
vx *= friction;
hero.x += vx;
hero.y += vy;
checkGroundCollision();
checkWalls();
}
There's a function to check which key has been pressed:
function onKeyIsDown(event:KeyboardEvent):void {
switch (event.keyCode) {
case 87 :
if (inAir() == true) {
jump = false;
} else {
jump = true;
}
break;
case 65 :
ax = -1.5;
break;
case 68 :
ax = 1.5;
break;
case 83 :
break;
default :
break;
}
}
The inAir function checks whether or not the main character is in the air (yeah, really):
function inAir():Boolean {
if (hero.y < ground.y - ground.height / 2 - hero.height / 2) {
return true;
} else {
return false;
}
}
Last but not least there's a groundCollision function that checks whether the character has hit the ground, and it sets the 'jump' Boolean to false if it has.
function checkGroundCollision():void {
if (hero.hitTestObject(ground)) {
hero.y = ground.y - ground.height / 2 - hero.height / 2;
jump = false;
}
}
The actual problem :/
When I press the 'w' key I get different results. Sometimes the character jumps very high, sometimes the character jumps very low. I thought when the W key is pressed it called the EnterFrame function every time, meaning that it would only 'jump' only once (because of the 'jump' boolean), apparently it doesn't. What am I doing wrong here?
Here's the .swf so you can see it for yourself.