unity 鼠标拖拽旋转 3d物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectRotation : MonoBehaviour
{
public float rotationSpeed = 1.0f; // 旋转速度
private Vector3 lastMousePosition; // 上一个鼠标位置
bool isRotate;
public void Start()
{
}
private void Update()
{
if(isRotate)
{
if (Input.GetMouseButton(0))
{
float deltaX = Input.mousePosition.x - lastMousePosition.x;
float deltaY = Input.mousePosition.y - lastMousePosition.y;
Debug.Log("按住右键旋转");
transform.Rotate(Vector3.up, deltaX * rotationSpeed * Time.deltaTime, Space.World);
transform.Rotate(-Vector3.left, deltaY * rotationSpeed * Time.deltaTime, Space.Self);
}
float scroll = Input.GetAxis("Mouse ScrollWheel");
transform.Translate(Vector3.forward * scroll * rotationSpeed * Time.deltaTime);
lastMousePosition = Input.mousePosition;
}
}
public void OnMouseDown()
{
lastMousePosition = Input.mousePosition;
isRotate = true;
}
public void OnMouseUp()
{
isRotate = false;
}
}
脚本挂载需要操作的物体身上