滑动屏幕旋转相机
本文关键字:相机 旋转 屏幕 | 更新日期: 2023-09-27 18:08:41
我正在用Unity3D为智能手机编写一款3D游戏,不知道如何制作镜头旋转(第一人称视角)。
制作虚拟操纵杆太难了,所以我决定让镜头在滑动屏幕时旋转。
用户滑动智能手机屏幕,相机转动。
旋转工作,但总是从同一位置开始。
保存最后一个位置将破坏所有旋转(旋转是歪斜的)。
我代码:using UnityEngine;
using System.Collections;
public class Look : MonoBehaviour {
public float sensitivityX = 1F;
public float sensitivityY = 1F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -25F;
public float maximumY = 25F;
float rotationX = 0F;
float rotationY = 0F;
float oldRotationX = 0F;
float oldRotationY = 0F;
float lastX = 0F;
float lastY = 0F;
Quaternion originalRotation;
void Update ()
{
if (Input.touches.Length > 0)
{
if(Input.touches[0].phase == TouchPhase.Began)
{
lastX = Input.touches[0].position.x;
lastY = Input.touches[0].position.y;
rotationX = transform.localEulerAngles.x;
rotationY = transform.localEulerAngles.y;
oldRotationX = rotationX;
oldRotationY = rotationY;
}
if(Input.touches[0].phase == TouchPhase.Moved)
{
rotationX = (oldRotationX + (Input.touches[0].position.x - lastX)) * sensitivityX;
rotationY = (oldRotationY + (Input.touches[0].position.y - lastY)) * sensitivityY;
rotationX = ClampAngle (rotationX, minimumX, maximumX);
rotationY = ClampAngle (rotationY, minimumY, maximumY);
Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, -Vector3.right);
transform.localRotation = originalRotation * xQuaternion * yQuaternion;
}
//this should make rotating from last position, but it
//makes rotating incorrect (askew)
//without code below rotating works, but on always
//starts from the same position
if(Input.touches[0].phase == TouchPhase.Ended)
{
originalRotation = transform.localRotation;
}
}
}
void Start ()
{
if (rigidbody)
rigidbody.freezeRotation = true;
originalRotation = transform.localRotation;
}
public static float ClampAngle (float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp (angle, min, max);
}
}
请帮帮我。谢谢。
您可以使用输入,特别是触摸位置。然后,您可以应用在鼠标外观脚本中实现的类似效果。
基本上你想要的代码是:
rotationX += Input.touches[0].position.x * sensitivityX;
rotationY += Input.touches[0].position.y * sensitivityY
Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, -Vector3.right);
transform.localRotation *= xQuaternion * yQuaternion;
if(Input.touches.Length > 0 && Input.GetTouch(0).phase == TouchPhase.Moved){
transform.Rotate(new Vector3(-Input.GetTouch(0).deltaPosition.y,Input.GetTouch(0).deltaPosition.x,0)*speed*Time.deltaTime);
transform.rotation=Quaternion.Euler(transform.rotation.eulerAngles.x,transform.rotation.eulerAngles.y,0);
}