0

我有一个 3d 无限赛跑者赛车类型游戏,其中玩家是静止的,而背景是移动的。在我的游戏中,我想随着时间的推移随机生成硬币,并且硬币必须在玩家之前非常多地生成,并且硬币的 z 轴会减少,同时保持 y 轴恒定和 x 轴值在 -2 和的随机范围内2. 硬币生成正确,但生成方式不规则。我在我的场景中创建了四个硬币游戏对象,我想以一条直线生成 4 个硬币,因为玩家可以轻松收集硬币,因为它们以一条直线向玩家走来。玩家的运动仅在从 -2 到 2 的 x 轴上。现在我的问题是硬币生成不规则,因为玩家无法轻松收集硬币。这是我的代码:

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));

    }
}

硬币生成正确,但顺序不规则。有人可以帮我吗?在此先感谢..由于我是统一的新手,我什至不知道我的游戏逻辑是否正确。如果我在代码中的某些地方有错误,有人可以用代码纠正我吗?

4

1 回答 1

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;
}
于 2014-11-06T20:52:58.637 回答