Question

so I haven't started quite yet, but I want to make a simple d-pad for my application in flash AS3. So let's just say I have four buttons. UpBtn, DownBtn, LeftBtn, and RightBtn. I want to simply just move an object in those directions. Let's say the objects name is "manD". How would I do this in AS3?

A simple D-Pad like below

Was it helpful?

Solution

You could do something like this (all your buttons do need a name and your man:

var speed:int = 10;
var xdir:int = 0;
var ydir:int = 0;

UpBtn.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
DownBtn.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
LeftBtn.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
RightBtn.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
addEventListener(MouseEvent.MOUSE_UP, onUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);

// What happens when a button is released.
function onUp(e:MouseEvent):void {
    xdir = 0;
    ydir = 0;
}

// What is happening when one of the buttons is clicked.
function onDown(e:MouseEvent):void {
    // Reset direction
    onUp(e);

    switch(e.target.name){
        case 'LeftBtn':
            xdir = -1;
            break;
        case 'RightBtn':
            xdir = 1;
            break;
        case 'UpBtn':
            ydir = -1;
            break;
        case 'DownBtn':
            ydir = 1;
            break;
    }
}

// The actual movement.
function onEnterFrame(e:Event):void {
    manD.x += xdir * speed;
    manD.y += ydir * speed;
}

That should do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top