Skip to content

Instantly share code, notes, and snippets.

@stilllisisi
Created March 11, 2020 08:01
Show Gist options
  • Save stilllisisi/521584ce84672343d0a21b7ee8e5e875 to your computer and use it in GitHub Desktop.
Save stilllisisi/521584ce84672343d0a21b7ee8e5e875 to your computer and use it in GitHub Desktop.
【游戏-unity】Unity通过Terrain地形数据计算人物位置
//如何通过Terrain地形数据计算人物位置,比如当地形高度不在0点的时候,设置人物位置会出现问题,需要计算Terrain.activeTerrain.GetPosition().y的值
float height;
Vector3 newPos;
float halfModelY;
float terrainHeight;
private void SetModelHight()
{
if (GetComponent<MeshFilter>() != null)
{
halfModelY = GetComponent<MeshFilter>().sharedMesh.bounds.size.y * transform.lossyScale.y / 2;
}
}
// Update is called once per frame
void Update()
{
if (canMove)
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
if (Terrain.activeTerrain != null)
{
float height = Terrain.activeTerrain.SampleHeight(transform.position);
terrainHeight = Terrain.activeTerrain.GetPosition().y;
Debug.Log(height);
newPos.x = transform.position.x;
newPos.y = height + halfModelY+ terrainHeight;
newPos.z = transform.position.z;
transform.position = newPos;
}
}
}
@stilllisisi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment