ForumsProgramming ForumBasic Keyboard Movement in ActionScript 3

4 11830
SeoMX
offline
SeoMX
90 posts
210

Does anyone know how to make stuff move using the keyboard in ActionScript 3???

  • 4 Replies
ThexDancingxMuffin
offline
ThexDancingxMuffin
63 posts
50

onClipEvent (load) {
moveSpeed = ~3~;
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.~1~)) {
this._~2~+=moveSpeed;
}
}



EXPLAINING:
~1~: this is the key that you press to make the character make. Ex: spacebar, 2 key, G key, etc.
~2~: this is the axis that the object will move on. Y axis is horizontal and X axis is vertical.
~3~: this is the speed that it moves when you press a button. Pretty self-explanatory.



So, in the end, it would look something like this:



onClipEvent (load) {
moveSpeed = 15;
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.RIGHT)) {
this._x+=moveSpeed;
}
if (Key.isDown(Key.LEFT)) {
this._x-=moveSpeed;
}
if (Key.isDown(Key.DOWN)) {
this._y+=moveSpeed;
}
if (Key.isDown(Key.UP)) {
this._y-=moveSpeed;
}
}

ThexDancingxMuffin
offline
ThexDancingxMuffin
63 posts
50

**~1~: this is the key that you press to make the character move. Ex: spacebar, 2 key, G key, etc.

rwtwm
offline
rwtwm
6 posts
70

is that not AS2 code?

in Actionscript 3 all key inputs are dealt with event handlers.

To use these you need two things, a function to execute when the event occurs and an event listener on the stage to listen for keyboard input.

It looks like...

function <function name> (event:KeyboardEvent){
if(event.keyCode == Keyboard.LEFT){
<character name>.x -= <movement speed>
}
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, <function name>);

note that your movement function is also an argument of the event listener. The character name is whatever you want to move when the key is depressed.

Apathy
offline
Apathy
3 posts
30

There's a ton of tutorials that'll help if you if you search on any engine as well

Showing 1-4 of 4