unity鼠标拖动物体旋转
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 鼠标控制自旋 /// </summary> public class SpinWithMouse : MonoBehaviour { private bool isClick = false; private Vector3 nowPos; private Vector3 oldPos; float length = 1; void Start() { AddBoxCollider(); } void OnMouseUp() { //鼠标抬起 isClick = false; } void OnMouseDown() { //鼠标按下 isClick = true; } 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); } } oldPos = Input.mousePosition; } /// <summary> /// 添加Collider作为鼠标检测区域 /// </summary> public void AddBoxCollider() { BoxCollider box = gameObject.AddComponent<BoxCollider>(); //参数 box.center = new Vector3(0, 1.2f, 0); box.size = new Vector3(2.4f, 2.4f, 2.4f); } }
本来想用射线检测,发现unity生命周期自己带这个,挺方便的,脚本直接挂在物体上就行