PDA

View Full Version : I'm a newb! How to move with no diagonals



Bdizzle
August 28th, 2010, 03:31 AM
I'm using this code right now for a moving background:

onClipEvent (load) {
movespeed = 8;
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.RIGHT)) {
_x-= movespeed;
}
if (Key.isDown(Key.LEFT)) {
_x+= movespeed;
}
if (Key.isDown(Key.UP)) {
_y+= movespeed;
}
if (Key.isDown(Key.DOWN)) {
_y-= movespeed;
}
}
but the problem is that pressing combinations of arrows moves the background diagonally (up+left; down+right; etc.)

I do NOT want diagonal character movement at all! I just want up/down/left right. So how do I code this??

Also, is there a better way to write the code above to be shorter?

Thanks!! :megaman_classic:

ayumilove
August 28th, 2010, 07:25 AM
you should start moving to as3

Preview SWF Here
http://megaswf.com/serve/41252/

Below is Actionscript 3 solution to your issue


import flash.display.Sprite;
import flash.events.KeyboardEvent;
var speed:uint = 10;
var keyLock:uint;

// A dummy red square to demonstrate movement.
var sp:Sprite = new Sprite();
sp.graphics.beginFill(0xFF0000);
sp.graphics.drawRect(0,0,25,25);
sp.graphics.endFill();
super.addChild(sp);

super.stage.addEventListener(KeyboardEvent.KEY_DOW N, this.keyDownHandler);
Here is the meat of the code


function keyDownHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.LEFT : sp.x -= this.speed; break;
case Keyboard.RIGHT : sp.x += this.speed; break;
case Keyboard.UP : sp.y -= this.speed; break;
case Keyboard.DOWN : sp.y += this.speed; break;
default : break;
}
}