我正在使用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);
}
}
请帮帮我。感谢。
答案 0 :(得分:1)
您可以使用inputs,特别是触摸位置。然后,您可以在mouse look script中应用类似的效果。
基本上你想要的代码是:
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;
答案 1 :(得分:-1)
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);
}