实际上有没有一种快速的方法可以让地形“在你之下”——然后使用快速函数 .sampleHeight ?
是的,这是可以做到的。
(或者实际上,sampleHeight 只是一个相当无用的演示函数,只能在具有一个地形的演示中使用?)
不
有Terrain.activeTerrain
返回场景中的主要地形。还有Terrain.activeTerrains
(注意末尾的“s”)返回场景中的活动地形。
Terrain.activeTerrains
获取返回Terrain
数组的地形,然后使用Terrain.GetPosition
函数获取其位置。通过查找距离玩家位置最近的地形来获取当前地形。Vector3.Distance
您可以通过使用或Vector3.sqrMagnitude
(更快)对地形位置进行排序来做到这一点。
Terrain GetClosestCurrentTerrain(Vector3 playerPos)
{
//Get all terrain
Terrain[] terrains = Terrain.activeTerrains;
//Make sure that terrains length is ok
if (terrains.Length == 0)
return null;
//If just one, return that one terrain
if (terrains.Length == 1)
return terrains[0];
//Get the closest one to the player
float lowDist = (terrains[0].GetPosition() - playerPos).sqrMagnitude;
var terrainIndex = 0;
for (int i = 1; i < terrains.Length; i++)
{
Terrain terrain = terrains[i];
Vector3 terrainPos = terrain.GetPosition();
//Find the distance and check if it is lower than the last one then store it
var dist = (terrainPos - playerPos).sqrMagnitude;
if (dist < lowDist)
{
lowDist = dist;
terrainIndex = i;
}
}
return terrains[terrainIndex];
}
用法:
假设玩家的位置是transform.position
:
//Get the current terrain
Terrain terrain = GetClosestCurrentTerrain(transform.position);
Vector3 point = new Vector3(0, 0, 0);
//Can now use SampleHeight
float yHeight = terrain.SampleHeight(point);
虽然可以使用 来做到这一点Terrain.SampleHeight
,但这可以通过从玩家位置到地形的简单光线投射来简化。
Vector3 SampleHeightWithRaycast(Vector3 playerPos)
{
float groundDistOffset = 2f;
RaycastHit hit;
//Raycast down to terrain
if (Physics.Raycast(playerPos, -Vector3.up, out hit))
{
//Get y position
playerPos.y = (hit.point + Vector3.up * groundDistOffset).y;
}
return playerPos;
}