如果我在场景中有一个地形,这个脚本就能正常工作,但是我没有地形--这个例子:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class SpawnObjects : MonoBehaviour
{
public GameObject prefab;
public Terrain terrain;
public int numberOfObjects;
public float duration;
public float yOffset = 0.5f;
private float terrainWidth;
private float terrainLength;
private float xTerrainPos;
private float zTerrainPos;
void Awake()
{
//Get terrain size
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
//Get terrain position
xTerrainPos = terrain.transform.position.x;
zTerrainPos = terrain.transform.position.z;
StartCoroutine(Generate());
}
IEnumerator Generate()
{
//Generate the Prefab on the generated position
for (int i = 0; i < numberOfObjects; i++)
{
//Generate random x,z,y position on the terrain
float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));
//Apply Offset if needed
yVal = yVal + yOffset;
GameObject objInstance = (GameObject)Instantiate(prefab,
new Vector3(randX, yVal, randZ), Quaternion.identity);
if (duration > 0)
{
yield return new WaitForSeconds(duration);
}
}
}
}在我的场景中,我有一些山体,不是我自己的,而是一个包裹。我想在群山周围随意产卵。

其中一个山体的例子:

发布于 2022-09-09 23:03:52
因为你的地形有一个网格对撞机,你可以Raycast。光线广播基本上是从一个点模拟一条线,向一个方向走,直到它撞上对撞机。链接中的信息。
如何使用它
y设为一个大于山高的数。它的代码:
...// in class
float fromX, toX, fromZ, toZ;
RaycastHit hit;
...
//In the coroutine
Vector3 mPos = mesh.bounds.center + transform.position;
fromX = -mesh.bounds.extents.x + mPos.x;
toX = mesh.bounds.extents.x + mPos.x;
fromZ = -mesh.bounds.extents.z + mPos.z;
toZ = mesh.bounds.extents.z + mPos.z;
float randX = Random.Range(fromX, toX);
float randZ = Random.Range(fromZ, toZ);
Vector3 checkPos = new Vector3(randX, 999f, randZ);
if (Physics.Raycast(checkPos, Vector3.down, our hit)
{
Vector3 OUTPUT = hit.point;
}
else
{
Debug.Log("No point found");
}
...编辑:
如果您想自动获得toX,获取mesh.bounds.extents.x + mesh.bounds.center + transform.position。我编辑了脚本
https://stackoverflow.com/questions/73667526
复制相似问题