计算所需位置,以在旋转相机时保持对象居中

时间:2019-03-02 21:17:27

标签: c# unity3d math

我一直想将物体放在相机的视线中央。 该对象无法更改其位置。

可以旋转相机。 相机可以上下移动。 该对象应始终位于相机视图的中心。

因此,当我将相机旋转-45°时,我想知道相机的Y位置,旋转后的相机仍将直接面对对象。

我知道相机和物体之间的“水平”距离(因为它永远不会改变),而且我知道相机的角度。

如何计算“所需的摄像机位置Y值”?

谢谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

所以这段代码对我有用:

//Distance between object and camera. Y-axis is pointing up, so we use x and z coordinates.
float R = Vector2.Distance(new Vector2(obj.position.x, obj.position.z),
                            new Vector2(camera.transform.position.x, camera.transform.position.z));
// Lets find rotation from zero to target angle   
float rAngle = Mathf.Deg2Rad * (camera.transform.rotation.eulerAngles.y + angle );
// Using minus cause when we rotate camera to the "right" we have to move it to the"left"
        float x = -R * Mathf.Sin(rAngle);
        float y = -R * Mathf.Cos(rAngle);

// Apply changes.
camera.transform.position = new Vector3(x, camera.transform.position.y, y);
Vector3 cameraRotation = new Vector3(0,  angle,0);
camera.transform.Rotate(cameraRotation);

正如我所说,您可以轻松使用https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html