如何通过缩放视野始终保持 2 个物体在视野中?(或 z&y 轴) [英] How to keep 2 objects in view at all time by scaling the field of view? (or z&y axis)
本文介绍了如何通过缩放视野始终保持 2 个物体在视野中?(或 z&y 轴)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为 2 个玩家制作一个小型街机射击游戏,并且需要让屏幕聚焦在 2 个玩家上,我让相机在 X 轴的玩家中心移动,但我认为这会很酷当 2 个玩家靠得更近时,相机也会靠得更近.
I'm making a little arcade shooter for 2 players, and need to have the screen focused on 2 players, I got the camera moving in the center of the players in the X axis, but it I think it would be cool when the 2 players get closer together the camera also get closer.
这是透视图:
推荐答案
移动相机比改变 fov 更好.计算相机距离的公式为
Moving the camera is better than changing the fov. The formula for calculating the camera distance is
cameraDistance = (distanceBetweenPlayers / 2 / aspectRatio) / Tan(fieldOfView / 2);
注意玩家出现在视口的最边缘,因此可以添加一些小的边距.这是我的脚本:
Note the players appear on the very edge of the viewport thus some small margin could be added. Here is my script again:
public Transform player1;
public Transform player2;
private const float DISTANCE_MARGIN = 1.0f;
private Vector3 middlePoint;
private float distanceFromMiddlePoint;
private float distanceBetweenPlayers;
private float cameraDistance;
private float aspectRatio;
private float fov;
private float tanFov;
void Start() {
aspectRatio = Screen.width / Screen.height;
tanFov = Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView / 2.0f);
}
void Update () {
// Position the camera in the center.
Vector3 newCameraPos = Camera.main.transform.position;
newCameraPos.x = middlePoint.x;
Camera.main.transform.position = newCameraPos;
// Find the middle point between players.
Vector3 vectorBetweenPlayers = player2.position - player1.position;
middlePoint = player1.position + 0.5f * vectorBetweenPlayers;
// Calculate the new distance.
distanceBetweenPlayers = vectorBetweenPlayers.magnitude;
cameraDistance = (distanceBetweenPlayers / 2.0f / aspectRatio) / tanFov;
// Set camera to new position.
Vector3 dir = (Camera.main.transform.position - middlePoint).normalized;
Camera.main.transform.position = middlePoint + dir * (cameraDistance + DISTANCE_MARGIN);
}
这篇关于如何通过缩放视野始终保持 2 个物体在视野中?(或 z&y 轴)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文