using UnityEngine;
public class ObjectRotation : MonoBehaviour
{
public float rotateSpeed = 5.0f;
private Vector3 lastMousePosition;
void Update()
{
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
Vector3 deltaPosition = touch.deltaPosition;
transform.Rotate(Vector3.down * deltaPosition.x * rotateSpeed * Time.deltaTime, Space.World);
transform.Rotate(Vector3.right * deltaPosition.y * rotateSpeed * Time.deltaTime, Space.World);
}
}
}
}
代码中的Space.World表示着这个物体是以世界坐标来进行旋转的,如果要实现以自身坐标进行旋转这要以下代码
using UnityEngine;
public class ObjectRotation : MonoBehaviour
{
public float rotateSpeed = 5.0f;
private Vector2 lastTouchPosition;
void Update()
{
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
Vector2 deltaPosition = touch.position - lastTouchPosition;
float deltaX = deltaPosition.x / Screen.width * rotateSpeed;
float deltaY = deltaPosition.y / Screen.height * rotateSpeed;
transform.Rotate(Vector3.up, -deltaX, Space.Self);
transform.Rotate(Vector3.right, deltaY, Space.Self);
}
lastTouchPosition = touch.position;
}
}
}
以上代码是用GPT写出来的。