首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算在相机旋转时保持对象居中所需的位置

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

Stack Overflow用户
提问于 2019-03-03 05:17:27
回答 1查看 221关注 0票数 0

我总是想把一个物体放在相机的中心位置。对象不能更改其位置。

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

因此,当我将相机旋转-45°时,我想知道相机的Y位置,在这个位置,旋转的相机仍然直接面对物体。

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

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

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-03 07:20:09

所以这段代码对我来说是有效的:

代码语言:javascript
复制
//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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54963083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档