I have a character imported to my stage, but I want a button called "Random" that when hit, moves the character either up down left or right, every time you click it. Here's what I tried, but the character will just move diagonally.
//import the code to use the components
import fl.events.ComponentEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
//stay on this frame
stop();
//declare variables
var RandomNumber:Number = Math.floor(Math.random() * 5) -5;
var XMove:Number;
var YMove:Number;
var tmrMove:Timer = new Timer(25);
btnRandom.addEventListener(ComponentEvent.BUTTON_DOWN, RandomNum);
//listen for timer to tick
tmrMove.addEventListener(TimerEvent.TIMER, onTick);
function RandomNum(e:ComponentEvent) {
XMove = RandomNumber;
YMove = RandomNumber;
tmrMove.start()
}
//function for timer
function onTick (e:TimerEvent) {
//move the ninja
picNinja.x = picNinja.x + XMove;
picNinja.y = picNinja.y + YMove;
//check if ninja goes off stage
if (picNinja.x > stage.stageWidth) {
picNinja.x = 0;
}
if (picNinja.x < 0) {
picNinja.x = stage.stageWidth;
}
if(picNinja.y > stage.stageHeight) {
picNinja.y = 0;
}
if(picNinja.y < 0) {
picNinja.y = stage.stageHeight;
}
//function to stop the timer
function stopApp (e:ComponentEvent) {
tmrMove.stop();
}
I thought assigning a random value would work(between 5 and -5) but something is definitely wrong here.
In your code, XMove is always equal to YMove, and the value of RandomNumber won't change when you call RandomNum(e:ComponentEvent) function.so the character will just move diagonally.
Try this.