在flash中随机移动角色

在flash中随机移动角色,flash,actionscript,Flash,Actionscript,我有一个角色导入到我的舞台上,但我想要一个名为“随机”的按钮,当你点击它时,它会将角色左右上下移动。这是我尝试过的,但角色只会沿对角线移动 //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 variable

我有一个角色导入到我的舞台上,但我想要一个名为“随机”的按钮,当你点击它时,它会将角色左右上下移动。这是我尝试过的,但角色只会沿对角线移动

//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();
}
//导入代码以使用组件
导入fl.events.ComponentEvent;
导入flash.utils.Timer;
导入flash.events.TimerEvent;
//呆在这个架子上
停止();
//声明变量
var RandomNumber:Number=Math.floor(Math.random()*5)-5;
var XMove:编号;
变量YMove:数字;
var TMR移动:定时器=新定时器(25);
btnRandom.addEventListener(ComponentEvent.BUTTON_向下,随机数);
//听计时器滴答作响
tmrMove.addEventListener(TimerEvent.TIMER,onTick);
函数RandomNum(e:ComponentEvent){
XMove=随机数;
YMove=随机数;
tmrMove.start()
}
//定时器功能
函数onTick(e:TimerEvent){
//移动忍者
picNinja.x=picNinja.x+XMove;
picNinja.y=picNinja.y+YMove;
//检查忍者是否离开舞台
if(picNinja.x>舞台宽度){
picNinja.x=0;
}
if(picNinja.x<0){
picNinja.x=stage.stageWidth;
}
if(picNinja.y>stage.stageHeight){
小忍者y=0;
}
if(picNinja.y<0){
picNinja.y=stage.stageHeight;
}
//函数停止计时器
函数stopApp(e:ComponentEvent){
tmrMove.stop();
}

我原以为分配一个随机值会起作用(在5到-5之间),但这里肯定有问题。

在您的代码中,XMove始终等于YMove,并且当您调用RandomNum(e:ComponentEvent)函数时,randomnume的值不会改变。因此,角色只会沿对角线移动

试试这个

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()
}