将一下脚本,挂载在要拖拽旋转的物体上
实例代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinWithMouse : MonoBehaviour
{
private bool isClick = false; //鼠标是否按下
private Vector3 nowPos; //现在的触摸位置
private Vector3 oldPos; //上一次的触摸的位置
private float length = 2f; //鼠标拖拽的距离 是否超过了2
//当鼠标抬起
private void OnMouseUp()
{
isClick = false;
}
//当鼠标按下
private void OnMouseDown()
{
isClick = true;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//获取现在的鼠标位置
nowPos = Input.mousePosition;
if (isClick) {//当鼠标按下
//现在的鼠标位置 减去上一次的鼠标位置 得到一个向量
Vector3 offset = nowPos - oldPos;
if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y) && Mathf.Abs(offset.x) > length) {
//让物体旋转
transform.Rotate(Vector3.up,-offset.x * 0.9f);
}
}
//获取上一次的鼠标位置
oldPos = Input.mousePosition;
}
}