对相机Zoom操作,不做聚焦触摸点处理时,放大手势后的相机视口如图红色细框所示:
前篇:Zoom简单实现-Unity透视相机下地图边界处理-海岛奇兵4
- 白色背景是地图模型;
- 红框和黑框都是相机视口区域。黑框是初始(操作前)相机视口,红色细框是优化前放大手势后的相机视口,红色粗框是优化后相机视口;
- 坐标系以 [初始(操作前)相机视口] 的中心为坐标原点(0,0)
我所做的缩放(Zoom)聚焦,原理是相机距离变化的同时,移动相机。效果上相当于以触摸点为中心操作。
那么,移动向量要怎么计算呢?
MoveVector = pos - newPos;
具体计算如下:
-
放大手势触摸点_gesturePos = gesture.position:两个手指触摸点的中心。
twoFinger.position = new Vector2(
(fingers[twoFinger.finger0].position.x+fingers[twoFinger.finger1].position.x)/2,
(fingers[twoFinger.finger0].position.y+fingers[twoFinger.finger1].position.y)/2
);计算_gesturePos在屏幕上的比例
var wp = _gesturePos.x / Screen.width;
var hp = _gesturePos.y / Screen.height;
- 计算 pos和 newPos, newPos与pos 在当前相机视口的坐标比例相同
pos = (viewportWidth * (wp - 0.5), viewportHeight * (hp - 0.5))
newPos = (newWidth * (wp - 0.5), newHeight * (hp - 0.5))
- 计算视口Width、Height增量:increW、increH
// _IncreCameraDis: Zoom 缩放操作的本次距离操作增量
// _halfFOVTan = Mathf.Tan((_OriginalFov * 0.5f) * Mathf.Deg2Rad);
float increH = ((-_IncreCameraDis) * _halfFOVTan * 2);
float increW = (increH * _cameraMain.aspect);
计算透视相机视口宽高示意图.png
-
MoveVector = pos - newPos
MoveVector = pos - newPos = (viewportWidth * (wp - 0.5), viewportHeight * (hp - 0.5)) - (newWidth * (wp - 0.5), newHeight * (hp - 0.5)) = ((viewportWidth - newWidth) * (wp - 0.5), (viewportHeight - newHeight) * (hp - 0.5)) = increW * (wp - 0.5), increH * (wp - 0.5)
注意
取手势触摸点要注意的是,每次pinch手势过程只取Start那一次。
PinchEnd的时候重置,可以监听On_PinchEnd或On_TouchUp2Fingers事件。
public void OnPinchEnd(Gesture gesture)
{
_gesturePos = Vector2.zero;
}
代码
// 缩放聚焦
private void ZoomFocusing(Vector2 gesturePos)
{
if (_gesturePos == Vector2.zero) {
_gesturePos = gesturePos;
}
float increH = ((-_IncreCameraDis) * _halfFOVTan * 2);
float increW = (increH * _cameraMain.aspect);
var wp = _gesturePos.x / Screen.width;
var hp = _gesturePos.y / Screen.height;
_IncreMoveVector.x = (wp - 0.5f) * increW;
_IncreMoveVector.z = (hp - 0.5f) * increH;
}
网友评论