2014-10-31 76 views
0

我有一個3D無限亞軍賽車類型的遊戲,其中玩家是靜止的和背景移動。在我的遊戲中,我想隨時隨機產生硬幣,並且硬幣必須在玩家之前產生很多,並且硬幣的z軸減小,保持y軸恆定,x軸值在-2和-2的隨機範圍內。來自「簡明英漢詞典」這些硬幣產卵正確,但它們是以不規則的方式產生的。我在我的場景中創建了四個硬幣遊戲對象,我想直接產生4個硬幣,因爲玩家可以很容易地收集硬幣,因爲他們直接進入玩家。玩家的動作只在x軸上從-2到2.現在我的問題是硬幣不規則地產生,因爲玩家不能容易地收集硬幣。這是我的代碼:在無限亞軍3D遊戲中隨機產生硬幣

function Update() 
{ 
    MoveCoin(); 
} 

function MoveCoin() 
{ 
    ReleaseCoin(); 
    //CoinsOnRoad is an array containing the current coins which are on the road 
    //CoinPool is the array of coins 
    for(var i:int =0;i<CoinsOnRoad.length;i++) 
    { 
    var gcoin:GameObject = CoinsOnRoad[i] as GameObject; 
    gcoin.transform.position.z-=3*speed*Time.deltaTime; 
    if(gcoin.transform.position.z>=-10) 
    { 
     //Do nothing if the coin is on the visible area of the road. If it becomes invisible 
     //remove the coins from CoinsOnRoad Array and insert the coin back to the CoinPool Array 
    } 
    else 
    { 
     CoinPool.push(gcoin); 
     CoinsOnRoad.remove(gcoin); 

    } 

    } 
} 

function ReleaseCoin() 
{ 
    if(CoinPool.length==0) 
    { 

    } 
    else 
    { 
     var coin:GameObject=CoinPool.shift() as GameObject; 
     CoinsOnRoad.push(Instantiate(coin,new Vector3(Random.Range(-2.0,2.0),0.3,30+Random.Range(1,10)),Quaternion .identity)); 

    } 
} 

硬幣產卵正確,但不規則的順序。有人可以幫我嗎?先謝謝了。因爲我剛剛接觸團結,我不知道我的遊戲邏輯是否正確。如果我錯了代碼中的某處,有人可以用代碼糾正我。

+0

嘗試沒有的DeltaTime乘法 – LearnCocos2D 2014-10-31 08:10:29

+0

@ LearnCocos2D它亙古不變的工作.. – njnjnj 2014-10-31 08:16:51

回答

0

如果你想要硬幣產生直線,它可能只是幫助他們不會隨機產卵。

在你的循環中,你產生的每個硬幣都有不同的隨機位置。相反,您應該隨機選擇位置值並將其保存到變量中。然後你應該使用它在一個循環中產生多個硬幣。

像這樣:

var xPos = Random.Range(-2.0, 2.0); 
var forwardOffset = Random.Range(1, 10); 
var i = 0; 
var lineLength = Random.Range(1, CoinPool.length); 
while(i < lineLength) { 
    var coin:GameObject=CoinPool.shift() as GameObject; 
    CoinsOnRoad.push(Instantiate(coin,new Vector3(xPos, 0.3, 30 + forwardOffset + i), Quaternion.identity)); 
    i += 1; 
} 
+0

我不想實例化的方法,而不是我想要的對象池的方法,因爲對象池容易編程.. – njnjnj 2014-11-20 06:38:14

+0

然後用一個方法替換'Instantiate',該方法使用池來返回硬幣gameobject。 對象池簡單如實例化一堆對象離開屏幕並在隊列結構中跟蹤它們。當你想使用池中的對象時,你從該結構中出隊並使用該對象。當你完成對象時,將它移出屏幕並將其排入隊列,而不是使用「Destroy」。無論您如何提供硬幣對象,此硬幣放置方法都可以工作。 – Agumander 2014-11-20 16:53:51