前言
- 本文实现的功能是滑动屏幕的指定部分可以控制相机围绕着人物进行上、下、左、右的旋转操作
- 类似于蛋仔派对的旋转一样
实现原理
- 采用IDragHandler接口进行手指拖拽的监听
- 通过eventData获取滑动距离
- 根据滑动距离计算旋转角度
- 限制垂直旋转角度在一定范围内
- 计算相机的位置
- 应用旋转和位置到相机
demo展示
相机旋转控制视频演示
代码实现
public class CameraSwipeRotation : MonoBehaviour, IDragHandler
{
public Transform target; // 指定的物体
public float rotationSpeed = 1.0f; // 旋转速度
public float distance = 5.0f; // 相机与目标物体的距离
private float yaw = 0.0f;
private float pitch = 0.0f;
public void OnDrag(PointerEventData eventData)
{
// 获取滑动的距离
float deltaX = eventData.delta.x;
float deltaY = eventData.delta.y;
// 根据滑动距离计算旋转角度
yaw += deltaX * rotationSpeed;
pitch -= deltaY * rotationSpeed;
// 限制垂直旋转角度在一定范围内
pitch = Mathf.Clamp(pitch, -80.0f, 80.0f);
// 计算相机的位置
Vector3 offset = Quaternion.Euler(pitch, yaw, 0.0f) * new Vector3(0.0f, 0.0f, -distance);
Vector3 newPosition = target.position + offset;
// 应用旋转和位置到相机
transform.rotation = Quaternion.Euler(pitch, yaw, 0.0f);
transform.position = newPosition;
}
}