在Unity中,如何使用随机数量的高度和对象创建多个Spheres游戏对象?

时间:2016-08-24 19:08:08

标签: c# unity3d unityscript unity5

我想要的是制作一个脚本,该脚本将在Terrain随机数量的游戏对象上创建,在这种情况下为Spheres,并且每个游戏对象将具有随机高度。

using UnityEngine;
using System.Collections;

public class Random_Objects : MonoBehaviour {

    public int Random_Object_Min = 1, Random_Object_Max = 51;
    public int Random_Height_Min = 5, Random_Height_Max = 100;
    [HideInInspector] private int[] Objects_Number;
    [HideInInspector] private int[] Random_Heights;
    [HideInInspector] private int Area_Size_To_Build = 0;
    [HideInInspector] private Vector3 terrainSize;
    [HideInInspector] private GameObject s;
    [HideInInspector] private ArrayList myNodes;

    // Use this for initialization
    void Start () {

        Objects_Number = new int[Random.Range (Random_Objects_Min,Random_Objects_Max)];
        Random_Heights = new int[Random.Range(Random_Height_Min, Random_Height_Max)];

        myNodes = new ArrayList ();
        for (int i = 0; i < Objects_Number.Length; i++) 
        {
            s = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            s.transform.position = new Vector3 ((Random.value*461)+10, (Random.value*300)+10, 0F);
            //s.transform.localScale += new Vector3(

            myNodes.Add(s);
        }
    }

    // Update is called once per frame
    void Update () {

    }
}

我面临的第一个问题是当我创建int数组时,我在数组中得到随机位置,例如7个索引。但我也想分配随机高度,也可能是随机位置。

因此,如果我从示例7中获取Objects_Number,那么在每个中我想要一些值,例如每个随机高度和每个随机位置。

然后在For循环中一些如何提取这个随机值并创建随机Spheres。所以最后在ArrayList myNodes中我会像:

0 =位置(5,67,0)比例(30,4,0)

1 =位置(50,67,0)比例(1,40,0)

等等。后来我想在运行游戏时创建Spheres以在Terrain中显示它们。

1 个答案:

答案 0 :(得分:2)

创建代码: terrain sphere

创建图层: terrain

<强>地形

将地形添加到场景中,提示:为了能够绘画,您必须首先为其指定纹理。

terrain 标记和图层分配给地形。

确保它居中,默认大小似乎为500,因此x / z应为-250。

enter image description here

<强>代码

这会将球体随机放置在地形上方,但确保高度符合以下地形:

using System;
using UnityEngine;
using Random = UnityEngine.Random;

[ExecuteInEditMode]
public class SphereBuilder : MonoBehaviour
{
    // for tracking properties change
    private Vector3 _extents;
    private int _sphereCount;
    private float _sphereSize;

    /// <summary>
    ///     How far to place spheres randomly.
    /// </summary>
    public Vector3 Extents;

    /// <summary>
    ///     How many spheres wanted.
    /// </summary>
    public int SphereCount;

    public float SphereSize;

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        SphereCount = Mathf.Max(0, SphereCount);
        SphereSize = Mathf.Max(0.0f, SphereSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        SphereCount = 100;
        SphereSize = 20.0f;
    }

    private void Update()
    {
        UpdateSpheres();
    }

    private void UpdateSpheres()
    {
        if (Extents == _extents && SphereCount == _sphereCount && Mathf.Approximately(SphereSize, _sphereSize))
            return;

        // cleanup
        var spheres = GameObject.FindGameObjectsWithTag("Sphere");
        foreach (var t in spheres)
        {
            if (Application.isEditor)
            {
                DestroyImmediate(t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < SphereCount; i++)
        {
            var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            o.tag = "Sphere";
            o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            var y = Extents.y; // sphere altitude relative to terrain below
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.NameToLayer("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            // place !
            o.transform.position = new Vector3(x, y, z);
        }

        _extents = Extents;
        _sphereCount = SphereCount;
        _sphereSize = SphereSize;
    }
}

如果地形不是以零为中心,您还可以获得地形的网格边界并相应地放置球体。

<强>结果

enter image description here

enter image description here

下一步是什么?

相关问题