ForumsProgramming ForumBasic Keyboard Movement in ActionScript 3

4 13526
SeoMX
offline
SeoMX
89 posts
Nomad

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

  • 4 Replies
ThexDancingxMuffin
offline
ThexDancingxMuffin
61 posts
Nomad

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
61 posts
Nomad

**~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
Nomad

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&gt;

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
Nomad

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

Showing 1-4 of 4