News:

If you need instructions on how to get through the hotels, check out the enclosed instruction book.

Main Menu

AS3 Help

Farted by AmberArachnidClock, June 22, 2010, 09:25:49 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

AmberArachnidClock

I've started the process of switching to actionscript 3 and I've run into a little problem. I'm trying to have a keyboard-controlled character. I'm using the code below:
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onKeyPressed(evt:KeyboardEvent):void {
switch (evt.keyCode){
case Keyboard.LEFT:
bg.x += 4;
break;
case Keyboard.RIGHT:
bg.x -= 4;
break;
}
}


The problem is that when the key is held down, the object moves for one frame, then there is a pause, then the object moves continually. I'm trying to remove that pause so that the object will continuously move without that little jerk in the beginning.

Any suggestions?

BootClock

The problem you are having is to do with how systems interpret key presses. Check it out hold down a letter in the quick reply box it will put one then pause for a second then start spilling many out in the same way that your bg was moving.

Anyway one way I can see to do it is the following code:

var left:Boolean = false;
var right:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onKeyPressed(evt:KeyboardEvent):void {
switch (evt.keyCode){
case Keyboard.LEFT:
left = true;
break;
case Keyboard.RIGHT:
right = true;
break;
}
}
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
function onKeyReleased(evt:KeyboardEvent):void {
switch (evt.keyCode){
case Keyboard.LEFT:
left = false
break;
case Keyboard.RIGHT:
right = false
break;
}
}
stage.addEventListener(Event.ENTER_FRAME, eFrame);
function eFrame(Event) {
if (left) {
bg.x += 4;
}
if (right) {
bg.x -= 4;
}
}


It will now move smoothly however the speed is now based upon the frame rate, so the higher the frame rate the faster it moves and the opposite for a lower frame rate. Previously your bg would have moved at the same speed independent of the frame rate.

Hope this helps :D

AmberArachnidClock

Great, thank you

BootClock

No problem friend.