在随机生成的世界点上产生对象

0 c# unity-game-engine unity5

我是团结3D的新手,我想做一个非常简单的障碍课程游戏.我不希望它有多个级别,但只有一个场景会在每次有人开始游戏时随机生成.

这是一张更好地解释这个想法的图片:

在此输入图像描述

在每个突出显示的部分中,每次应用程序启动时都会生成一个墙,并且玩家只能通过一个间隙,该间隙将在每个部分的任何区域a,b或c中随机生成.我试着查看这个,但这个例子并不多.

如有任何疑问,请不要犹豫.我总是收到回应通知.

谢谢你的时间!

Man*_*mer 6

基本概念:

  1. 从你的障碍物创建一个预制件
  2. 创建一个脚本(例如WallSpawner),其中包含几个参数(每个墙之间的距离,可能的位置等),并将其附加到场景中的对象(Walls例如,在您的情况下).
  3. StartAwake方法中,创建预制件的副本Instantiate并传入随机拾取的位置.

示例脚本:

public class WallSpawner : MonoBehaviour
{
    // Prefab
    public GameObject ObstaclePrefab;

    // Origin point (first row, first obstacle)
    public Vector3 Origin;

    // "distance" between two rows
    public Vector3 VectorPerRow;

    // "distance" between two obstacles (wall segments)
    public Vector3 VectorPerObstacle;

    // How many rows to spawn
    public int RowsToSpawn;

    // How many obstacles per row (including the one we skip for the gap)
    public int ObstaclesPerRow;

    void Start ()
    {
        Random r = new Random();

        // loop through all rows
        for (int row = 0; row < RowsToSpawn; row++)
        {
            // randomly select a location for the gap
            int gap = r.Next(ObstaclesPerRow);
            for (int column = 0; column < ObstaclesPerRow; column++)
            {
                if (column == gap) continue;

                // calculate position
                Vector3 spawnPosition = Origin + (VectorPerRow * row) + (VectorPerObstacle * column);
                // create new obstacle
                GameObject newObstacle = Instantiate(ObstaclePrefab, spawnPosition, Quaternion.identity);
                // attach it to the current game object
                newObstacle.transform.parent = transform;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例参数:

编辑器中的参数

示例结果:

示例墙(每行5个)