using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleport : MonoBehaviour {
public Vector3 terrainArea;
public float spinSpeed = 2.0f;
public int cloneTeleportations;
public GameObject prefab;
private bool rotate = false;
private bool exited = false;
private Transform[] teleportations;
private Random rnd = new Random();
private void Start()
{
GameObject go = GameObject.Find("Terrain");
Terrain terrain = go.GetComponent(Terrain);
terrainArea = terrain.terrainData.size;
for (int i = 0; i < cloneTeleportations; i++)
{
GameObject Teleportaion = Instantiate(prefab, new Vector3(Random.Range(i * 10.0F, i * 50.0F), 0, Random.Range(i * 10.0F, i * 50.0F)), Quaternion.identity);
Teleportaion.transform.parent = this.transform;
Teleportaion.transform.tag = "Teleportation";
}
}
}
现在有些游戏对象不在地形区域 . 我想要做的是保持克隆处于随机位置,但仅限于地形区域内 .
我如何在地形区域内实例化对象?
1 回答
我注意到你正在创建
Random
类的新实例 . 唐't do that with Unity' s Random API . 只需使用Random.Range生成随机数 .至于在地形上生成随机游戏对象:
1 . 找到X位置:
最终的随机X应该是:
2 . 找到Z位置:
最终的随机Z应该是:
3 . 找到Y位置:
y轴不必是随机的 . 虽然,如果您愿意,可以将其设为随机值 .
它只需要在地形上,以便实例化对象不会在地形下 .
这就是Terrain.SampleHeight到位的地方 . 您 must 使用此功能以完美地生成不在地形下的位置 . 您需要 #1 和 #2 的结果才能使用此结果:
如果要将偏移应用于y轴,现在可以在此时执行此操作 .
以下是一般示例 . 您必须使用此示例来扩展当前代码 .