2012-08-13 68 views
0

晚上好。我正在研究一个简单的项目,该项目使用EVENT_FRAME处理程序以矩形方式(右,上,左,下,重复)移动一个符号。这是我的代码使用ActionScript的矩形移动3

import flash.events.Event; 

var moveRate:Number = 20; 
var maxX:Number = 500; 
var minX:Number = 80; 
var maxY:Number = 60; 
var minY:Number = 320; 
var endOfLineX:int = 0; 
var endOfLineY:int = 0; 

roboSym.addEventListener(Event.ENTER_FRAME, move1); 
roboSym.addEventListener(Event.ENTER_FRAME, move2); 

    function move1(e:Event):void 
    { 
    if (endOfLineX == 0) 
    { 
     roboSym.x += moveRate; 
     if (roboSym.x >= maxX) 
     { 
       endOfLineX = 1; 
     } 
    } 
    else if (endOfLineX == 1) 
    { 
     roboSym.x -= moveRate; 
     if (roboSym.x <= minX) 
     { 
      endOfLineX = 0; 
     } 
    } 


    } 
    function move2(e:Event):void 
    { 

    if (endOfLineY == 0) 
    { 
     roboSym.y -= moveRate; 
     if (roboSym.y <= maxY) 
     { 
      endOfLineY = 1; 
     } 
    } 
    else if (endOfLineY == 1) 
    { 
     roboSym.y += moveRate; 
     if (roboSym.y >= minY) 
     { 
      endOfLineY = 0; 
     } 
    } 
    } 

事情是,运动保持对角线,而不是直线运动。我知道在我的逻辑中有一个错误,但我无法确定它是什么。

回答

1

那么你有2 EnterFrame事件,他们都有变量endOfLine,使他们都在同一时间垂直和水平,这会导致对角线运动。另外一个小技巧,你不必为EnterFame设置2个事件函数,你可以将move2中的代码粘贴到move1中,它仍然可以工作! 你基本上得到了这个:

function moveCombined(e:Event):void{ 
    if(endOfLineX == 1){ 
     roboSym.x += rate; 
     //So the robot moves horizontal 
    }else if(endOfLineX == 0){ 
     roboSym.x -= rate; 
     //It still moves horizontal but the other way 
    } 
    //And you do the same for the vertical motion 
    if(endOfLineY == 1){ 
     roboSym.y += rate; 
     //So the robot moves vertical 
    }else if(endOfLineY == 0){ 
     roboSym.y -= rate; 
     //It still moves vertical but the other way 
    } 
} 

所以每一帧,robotSym.x被添加(或减少)了速度,也robotSym.y被添加(或减少)了速度。这会创建一个对角线运动。

+0

我明白了!我终于明白了。我将endOfLine改为1个变量,名为endOfLine,并使其有4个状态(0,1,2和3),分别对应于右,上,左和下(然后重复)。非常有用的建议。谢谢托马斯先生! – Erasmus 2012-08-13 20:58:12