2014-11-24 52 views
0

新的AS3和試圖讓這個遊戲機制正常工作。我需要做的是讓每隻流星在屏幕上出現時立即向左移動,但它們根本不移動。如果有人知道如何解決這個問題,我將不勝感激!我將代碼分成兩部分,階段代碼和對象(流星)類代碼。AS3對象運動

以下是舞臺上的代碼。

import flash.events.MouseEvent; 
import flash.events.Event; 

var mcShip:Ship; 
var meteor:Meteor; 
var uiTimer:uint = 0; 
var aMeteors:Array = new Array(); 

function InitializeGame():void 
{ 
    mcShip= new Ship(); 
    mcShip.Initialize(100,200); 
    stage.addChild(mcShip); 
    stage.addEventListener(MouseEvent.MOUSE_MOVE, MouseInput); 
    stage.addEventListener(Event.ENTER_FRAME,GenerateMeteors); 
} 

function MouseInput(me_:MouseEvent):void 
{ 
    mcShip.Movement(me_); 
} 

function GenerateMeteors(eGenerate:Event):void 
{ 
    if (0 == ++uiTimer%10) 
    { 
     meteor= new Meteor(); 
     aMeteors.push(meteor); 
     meteor.Initialize(550, 390, 20); 
     stage.addChild(meteor); 

     trace (aMeteors); 
    } 
} 
InitializeGame(); 

下面是對象(流星)代碼。

import flash.events.Event; 
var speed:int; 
var aMeteors:Array = new Array(); 


function Initialize(iPosX_:int, iPosY_:int, iSpeed_:int):void 
{ 
    x = iPosX_; 
    y = Math.round(Math.random()* iPosY_) 
    speed = Math.round(Math.random() * iSpeed_); 
    var timer:Timer = new Timer(12) 
    timer.addEventListener(TimerEvent.TIMER,Update); 
    timer.start(); 

} 



function Update(ev_:Event):void 
{ 
    for (var a:int=0; a < aMeteors.length; a++) 
    { 
     aMeteors[a].x -= 1 * speed; 
    } 
} 

所以基本上,我試圖讓流星在x軸上向左移動。我確定我有很多問題妨礙了它的正確移動,但我無法弄清楚。感謝所有提前的幫助!所有的

回答

1

杉杉:產生一個隨機數,使用

Math.random() 

這會產生0和1之間的隨機數,要獲得0和400之間的數字,你可以通過400,然後乘以這個數使用

Math.round(number) 

要移動的小行星,首先你需要創建一個數組來儲存所有英寸

var asteroids:Array = new Array; 

您將需要一個帶有事件監聽器的計時器來添加它們。

var asteroidAdder:Timer = newTimer([delay],[repetitions or 0 for infinite repetitions]); 
asteroidAdder.addEventListener(TimerEvent.TIMER,addAsteroid); 

你應該讓addAsteroid爲它創建小行星的功能,並使用它添加到您的數組:

asteroids.push(asteroid); 

你的最後一步是添加其他定時器事件偵聽器,移動它們。讓它調用一個函數,也許'moveAsteroids'。在這個函數中應該是一個「for」循環,這樣的事情:

for (var a:int=0; a<asteroids.length; a++){ 
    asteroids[a].x+=asteroids[a].speed; 
} 

這將通過每個對象的陣列中(小行星[0]然後小行星[1]等)和移動他們的x位置由他們的速度。您可能還想添加檢查,看看他們何時離開屏幕邊緣。發生這種情況時,您可以通過for循環刪除它們:

removeChild(asteroids[a]); //removes the asteroid being checked from the stage 
asteroids.splice(a,1) //remove the asteroid at position 'a' in asteroids from the array 

希望這足以讓您順利。我認爲你對製作函數和使用事件監聽器有一定的瞭解。如果您有任何問題,請發表評論。

+0

謝謝,Trex。我仍然在努力解決這個問題,但你的迴應正在幫助我! – Eindigen 2014-11-24 09:29:56

+0

我修復了一些問題,Trex,但我更新了原始帖子,因爲我無法讓流星左移!再次感謝你的幫助。 – Eindigen 2014-11-24 12:20:38

+0

你的移動代碼看起來應該可以工作,儘管1 *可能是多餘的。你能告訴我當你運行代碼時究竟發生了什麼嗎?流星出現並保持靜止嗎? – Trex 2014-11-26 00:00:08