Move a character in flash randomly

44 views Asked by At

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.

1

There are 1 answers

0
fengsser On BEST ANSWER

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.

function getRandomNumber():Number{
 //return a random number in range. Math.random() * (max - min + 1)) + min;
    return Math.floor(Math.random() * (5  + 5 + 1)) -5; 
}

function RandomNum(e:ComponentEvent) {
    XMove = 0;
    YMove = 0;
    var direction:int = Math.floor(Math.random()*2);//horizontal or Vertical 
    //either up down left or right
    switch(direction){
         case 0:
             XMove = getRandomNumber();
             break;
         case 1:
             YMove = getRandomNumber();
             break;                   
    }

    tmrMove.start()
}