Unity通过Terrain地形数据计算人物位置

当地形高度不在0点的时候,设置人物位置会出现问题,需要计算Terrain.activeTerrain.GetPosition().y的值

float height;
    Vector3 newPos;
    float halfModelY;
    float terrainHeight;
    private void SetModelHight()
    {
        if (GetComponent() != null)
        {
            halfModelY = GetComponent().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;
            }
        }
    }

你可能感兴趣的:(【Unity】)