unity,手指滑动屏幕实现物体360度旋转

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写出来的。

猜你喜欢

转载自blog.csdn.net/qq_19829077/article/details/130095178