Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Unity] 根据 视口(Viewport) 偏移量计算 世界(World) 偏移量 #36

Open
yangruihan opened this issue Jan 19, 2021 · 0 comments

Comments

@yangruihan
Copy link
Owner

根据 视口(Viewport) 偏移量计算 世界(World) 偏移量

问题描述

制作跟随目标的镜头时,遇到需要给定一个视口百分比参数,使摄像机跟随进行一定的偏差,如下图:

image

图片来自于这里侵删

解决方案

一个取巧的方式:可以通过视口射线,来计算偏移量

 // 根据镜头偏移参数进行偏移
var ray1 = camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
var ray2 = camera.ViewportPointToRay(new Vector3(0.5f + screenOffset.x, 0.5f + screenOffset.y, 0f));

var cameraDistance = (camera.transform.position - target.transform.position).magnitude;
var worldPointScreenOffset = (ray2.origin + ray2.direction * cameraDistance)
                             - (ray1.origin + ray1.direction * cameraDistance);
finalPos = worldPointScreenOffset + camera.transform.position;

参考

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

No branches or pull requests

1 participant