// 单指旋转参数
public float rotationXSpeed = 0.05f;
public float rotationYSpeed = 0.05f;
private bool isZooming = false;
void Update()
{
if (Input.touchCount == 2)
{
// 双指触摸时只处理缩放
isZooming = true;
HandleZoom();
}
else if (Input.touchCount == 1)
{
// 单指触摸时只处理摄像机旋转
if (!isZooming)
{
HandleRotation();
}
}
else
{
// 重置缩放状态
isZooming = false;
}
}
void HandleZoom()
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
Vector2 touch0PrevPos = touch0.position - touch0.deltaPosition;
Vector2 touch1PrevPos = touch1.position - touch1.deltaPosition;
float prevTouchDeltaMag = (touch0PrevPos - touch1PrevPos).magnitude;
float touchDeltaMag = (touch0.position - touch1.position).magnitude;
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
float zoomDelta = deltaMagnitudeDiff * 0.01f * 1f; // 调整因子根据实际需求调整
float newFOV = Mathf.Clamp(PreviewCamera.fieldOfView - zoomDelta * zoomSpeed * 5f, minFOV, maxFOV);
if (!Mathf.Approximately(newFOV, PreviewCamera.fieldOfView))
{
// 使用 DOTween 实现缓动效果
DOTween.To(() => PreviewCamera.fieldOfView, x => PreviewCamera.fieldOfView = x, newFOV, 0.6f)
.SetEase(Ease.OutQuad); // 使用 Ease.OutQuad 可以产生更平滑的缓动效果
}
}
void HandleRotation()
{
if (!EventSystem.current.IsPointerOverGameObject())
{
UpdateRotation();
}
}
void UpdateRotation()
{
// 获取鼠标输入的旋转增量
float rotationXInput = Input.GetAxis("Mouse Y");
float rotationYInput = -Input.GetAxis("Mouse X"); // 调整这里的符号
// 根据旋转速度进行摄像机的旋转
if (maxHorizontalAngle == 180f || minHorizontalAngle == -180f)
{
targetRotationX += rotationXInput * rotationXSpeed;
targetRotationY += rotationYInput * rotationYSpeed;
}
else
{
// 对左右旋转角度进行限制
targetRotationY += rotationYInput * rotationYSpeed;
targetRotationY = Mathf.Clamp(targetRotationY, minHorizontalAngle, maxHorizontalAngle);
}
// 对上下旋转角度进行限制
targetRotationX += rotationXInput * rotationXSpeed;
targetRotationX = Mathf.Clamp(targetRotationX, minVerticalAngle, maxVerticalAngle);
Quaternion targetRotation = Quaternion.Euler(targetRotationX, targetRotationY, 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, lerpSpeed * Time.deltaTime);
}
问题记录:unity移动端单指进行rotation四元数旋转(固定机位旋转),双指进行缩放,从双指立马切换为单指会导致摄像机画面抖动的问题记录。
文章详细描述了在Unity中如何通过单指和双指触控分别控制摄像机的旋转和平移操作,包括使用`HandleRotation`和`HandleZoom`函数,以及利用`DOTween`实现平滑的缓动效果。
摘要由CSDN通过智能技术生成