Move Object with Keyboard question

Hello,

I know how to use the four arrow keys to move a ball around. Here’s the codes:

import flash.events.KeyboardEvent;

function moveBall(event:KeyboardEvent):void {
if (event.keyCode == 39) {
ball_mc.x += 1;
} else if (event.keyCode == 37) {
ball_mc.x -= 1;
} else if (event.keyCode == 38) {
ball_mc.y -= 1;
} else if (event.keyCode == 40) {
ball_mc.y += 1;
}

}

stage.addEventListener(KeyboardEvent.KEY_DOWN, moveBall);

The ball move a pixel when I press down the keys. I wish that when I press an arrow key (e.g. right arrow key), the ball will keep on moving right until I hit another arrow key (e.g. left arrow key). Then the ball will change moving in other direction (e.g. left).

I try to add a ENTER_FRAME event inside the moveBall function:
stage.addEventListener(Event.ENTER_FRAME, moveBall);
However it is not working and an error appear.

How can I do that?

Thanks and best regards

Alex

The moveBall method can only work when a KeyboardEvent is fired at it, but you’re on the right track with an enter frame listener. You need to combine the two.

Instead of having moveBall change the x / y position of ball_mc, have it set a variable ‘direction’ for example, e.g. direction = ‘up’;

Then have an enter frame function that uses that variable, probably with a switch. For example:


switch (direction)
{
     case 'up':
          ball_mc.y -= 1;
          break;

     case 'down':
          //etc...
}

Hello,

Thanks for your help. It is working now. Since I am new to Actionscript 3, I am not sure if this is the correct way to do it. Here’s my codes:

import flash.events.KeyboardEvent;

var direction:String;

function detectKey(event:KeyboardEvent):String {
if (event.keyCode == 39) {
direction = “right”;
} else if (event.keyCode == 37) {
direction = “left”;
} else if (event.keyCode == 38) {
direction = “up”;
} else if (event.keyCode == 40) {
direction = “down”;
} else if (event.keyCode == 32) {
direction = “stop”;
}

return direction;

}

function moveBall(evt:Event) {
switch (direction) {
case ‘up’ :
ball_mc.y -= 1;
break;

case ‘down’ :
ball_mc.y += 1;
break;

case ‘right’ :
ball_mc.x += 1;
break;

case ‘left’ :
ball_mc.x -= 1;
break;

case ‘stop’ :
// ENTER_FRAME event cannot be triggered again if add removeEventListener here
//stage.removeEventListener(Event.ENTER_FRAME, moveBall);
break;
}
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, detectKey);

stage.addEventListener(Event.ENTER_FRAME, moveBall);

Please check if the above codes can be improved.

It seems that the ENTER_FRAME event is running all the time. I am afraid that it will consume a lot of computer resources.

Is it possible that the ENTER_FRAME event is only triggered when the arrow keys are pressed. And the ENTER_FRAME event will be removed when the space bar is pressed.

Thanks and best regards

Alex