0

我想做一个无尽的跑步游戏。我有 2 个对象,一个在顶部,一个在底部。玩家必须在物体之间跳跃或蹲在物体上。我制作了一个创建这些对象的脚本,但有时两个对象是在同一个位置创建的,所以玩家不能做任何事情。如何解决?我可以检查 X 轴上的其他对象,但不能通过对撞机检查吗?

4

2 回答 2

1

基本上,您是在要求我们为您提供关卡生成器和游戏控制器源代码!你必须为你的游戏写一个。不是因为我们不想给你代码,而是因为每个游戏都必须有自己的。

对于初学者,您可以:

  • 将您的游戏区域拆分为一个矩阵,然后有一个某种数组,其中每个单元格可以有一个游戏对象或为空。然后游戏对象可以在该单元格内拥有自己的本地位置。显然一个单元格不能包含两个游戏对象。

  • 有一个关卡生成器,它告诉游戏控制器应该在哪里生成新对象。但是,您应该在关卡生成器中实现一些东西以防止重叠。

看看这个伪代码:

void FixedUpdate()
{
    if (player.transform.position.x + Half_of_screen_width_plus_margin > nextX)
    {
        Spawn(tmp[i].prefab, nextX);
        nextX += tmp[i].distanceToNext;
        i++;
    }

}

Half_of_screen_width_plus_margin是为了让游戏预见即将发生的事情

tmp[]是要实例化的(未实例化的)对象的集合。每个对象都是任意定义的。

如您所见,脚本每隔 fixedDeltaTime 秒检查下一个位置,并将屏幕末端的位置 x 与下一个位置 x 进行比较。如果通过,则创建下一个对象并将下一个位置 x 更改为另一个位置。

如果要使用随机生成,则应将 tmp[] 更改为 tmp。每次实例化都会生成下一个实例:

void FixedUpdate()
{
    if (player.transform.position.x + Half_of_screen_width_plus_margin > nextX)
    {
        Spawn(tmp.prefab, nextX);
        nextX += tmp.distanceToNext;

        tmp = generate_new_random_object();
    }

}
于 2017-02-02T19:09:52.323 回答
0

当您调用该函数来实例化您的游戏对象时,请检查最后一个游戏对象的 x 位置是否与您要使用的不同。

    private Vector3 LastObjectPosition, NewObjectPosition;
    private float minDistanceBetweenTwoObstacles = 5;

    public void InstantiateNewObstacle()
    {
        // Check if the x position of the new object isn't the same 
        // as the the x position of the last object
        if (NewObjectPosition.x != LastObjectPosition.x)
        {
            // Instantiate your gameobject
            MyInstantiate();
        }
        // Else increase the x value for the x position of the new object 
        // and then instantiate your gameobject
        else
        {
            NewObjectPosition.x += minDistanceBetweenTwoObstacles;
            MyInstantiate();
        }
    }

    public void MyInstantiate()
    {
        // Instantiate your prefab at the NewObjectPosition position
        Instantiate(new GameObject(), NewObjectPosition, new Quaternion());
        // Save the position of the new object as the position 
        // of the last object instantiated 
        LastObjectPosition = NewObjectPosition;
    }

希望这可以帮到你 !

于 2017-02-02T17:59:33.860 回答