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

时间:2017-08-10 11:32:30

标签: c# unity3d unity5

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

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

enter image description here

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

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

谢谢你的时间!

1 个答案:

答案 0 :(得分:6)

基本概念:

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

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

    示例参数:

    Parameters in the Editor

    示例结果:

    Example Walls (5 per row)

相关问题