2014-01-13 145 views
0

比方說,我有一個數組5個對象,我將所有他們沿x軸這樣的:移動物體

vx = 5; 

for (i:int = 0; i < objects.length; i++) 
{ 
objects[i].x += vx; 
} 

我想使這個。 如果數組'object'中的任何對象碰到PointA,則將該數組中的所有對象移動到左側,例如set vx * = -1;

我只能讓這個:

for (i:int = 0; i < objects.length; i++) 
{ 
// move right 
objects[i].x += vx; 

if (objects[i].hitTest(PointA)) 
{ 
    // move left 
    vx *= -1; 
} 
} 

這將改變對象的方向,但我需要等待所有OBJETS命中點A。

如何更改數組中所有對象的方向,如果它們中的任何一個碰到PointA?

+0

它看起來像你想改變方向一次**任何**的物體到達目的地,對嗎?您不打算立即將它們全部重置爲起源,而是一旦到達PointA就繼續遞增地移動它們。 – Atriace

回答

0

我不知道動作腳本,但你應該設置一個布爾值外的for循環,像bGoingRight

檢查,這是真實的,正確的移動物體,如果走錯一步的對象離開了。當你傳遞hitTest時,你應該把布爾值改爲false。

粗糙例

var bGoRight:Boolean = true; 

    for (i:int = 0; i < objects.length; i++) 
    { 
    if(bGoRight) 
    { 
    // move right 
    objects[i].x += vx; 
    } 
    else 
    { 
    // move left 
    vx *= -1; 
    } 

    if (objects[i].hitTest(PointA)) 
    { 
    // if any object hit the point, set the flag to move left 
    bGoRight = false; 
    } 
} 
+0

林不知道你是否明白我的問題。 –

+0

如果object1碰到pointA,我很容易將object1移動到左邊,然後如果object2碰到PointA,將object2移動到左邊等等......但是如何讓object1碰到PointA,將所有其他對象移動到左邊,而不僅僅是object1? –

+0

如果bGoRight設置爲false,則所有對象都將向左移動,因爲您將在繪製時檢查該對象。所以當一個對象碰到PointA時,只需將bGoRight從true切換到false。 – JMG

0

所以你需要檢查已經打到點A的對象,存儲它們,然後檢查更新的存儲數量相當於你的對象數組。然後,當這種情況下,你可以改變vx變量。這可能是這個樣子:

//set a variable for storing collided object references 
//note: if you are doing this in the IDE remove the 'private' attribute 
private var _contactList:Array = []; 

for (i:int = 0; i < objects.length; i++) 
{ 
    // move right 
    objects[i].x += vx; 

    if (objects[i].hitTest(PointA)) 
    { 
      if(contactList.length == objects.length) { 
      // move left 
      vx *= -1; 
      //clear our contact list 
      contactList.length = 0; 
      } 
      else if (noContact(objects[i])) { 
       contactList.push(objects[i]); 
      } 
    } 
} 

然後在其他功能if語句noContact(),如果你再在IDE中這樣做,你將需要刪除private屬性。

private function noContact(obj:*):Boolean { 
    if (contactList.indexOf(obj) != -1) { 
     return false; 
    } 
    return true; 
} 

你可以做到這一點的另一種方式是這樣的(如對方回答說一個布爾值的方式),但在你的存儲設置正確的依賴:

//set this variable for directionRight (boolean) 
private var directionRight:Boolean = true; 

for (i:int = 0; i < objects.length; i++) 
{ 
    // move right 
    objects[i].x += vx; 

    if (objects[i].hitTest(PointA)) 
    { 
      //we are moving to the right, object[i] is the last object 
      if(i == objects.length-1 && directionRight) { 
      // move left 
      directionRight = !directionRight; 
      vx *= -1; 
      } 
      else if (i == 0 && !directionRight)) { 
       // move right 
       directionRight = !directionRight; 
       vx *= -1; 
      } 
    } 
}