简体   繁体   English

在 Unity 中,如何创建具有随机数量的高度和对象的球体游戏对象?

[英]In Unity how can i create number of Spheres Game Objects with random number of Heights and objects?

What i want is to make a script that will create on a Terrain random number of gameObjects in this case Spheres and that it each one will have random Height.我想要的是制作一个脚本,该脚本将在这种情况下在地形随机数量的游戏对象上创建球体,并且每个游戏对象都将具有随机高度。

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 () {

    }
}

The first problem i face is when i create the int arrays i get random places in the array for example 7 indexs.我面临的第一个问题是,当我创建 int 数组时,我会在数组中获得随机位置,例如 7 个索引。 But i also want to assign random heights and maybe also random positions.但我也想分配随机高度,也可能是随机位置。

So if i get in Objects_Number fro example 7 then in each one i want to have some values like random height for each one and random position for each one.因此,如果我从示例 7 中获取 Objects_Number,那么在每个对象中,我都希望有一些值,例如每个对象的随机高度和每个对象的随机位置。

Then in the For loop some how to extract this random values and create the random Spheres.然后在 For 循环中一些如何提取这个随机值并创建随机球体。 So in the end in the ArrayList myNodes i will something like:所以最后在 ArrayList myNodes 中我会是这样的:

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

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

And so on.等等。 Later i want to create the Spheres to display them in the Terrain when running the game.后来我想创建球体以在运行游戏时在地形中显示它们。

Create tags: terrain , sphere创建标签:地形球体

Create layer: terrain创建图层:地形

Terrain地形

Add terrain to scene, tip: to be able to paint you must assign textures to it first.将地形添加到场景中,提示:要能够绘制,您必须先为其分配纹理。

Assign terrain tag and layer to terrain.为地形分配地形标记和图层。

Make sure it is centered, default size seems 500 so x/z should be -250.确保它居中,默认大小似乎是 500,所以 x/z 应该是 -250。

在此处输入图片说明

Code代码

This will place spheres randomly above terrain but ensures height is according terrain below:这会将球体随机放置在地形上方,但确保高度符合以下地形:

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

You could also get mesh bounds of your terrain and place spheres accordingly, if terrain is not zero-centered.如果地形不是以零为中心,您还可以获得地形的网格边界并相应地放置球体。

Result结果

在此处输入图片说明

在此处输入图片说明

What's next ?接下来是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM