Created
March 11, 2020 08:01
-
-
Save stilllisisi/521584ce84672343d0a21b7ee8e5e875 to your computer and use it in GitHub Desktop.
【游戏-unity】Unity通过Terrain地形数据计算人物位置
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//如何通过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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gameinstitute.qq.com/community/detail/128716