在这里只是提供一个旋转的方法,具体怎么实现,大家可以随意
using UnityEngine; using UnityEngine; using System.Collections; //选择旋转的轴向 public enum RotateEnum{ x_Axis, y_Axis, z_Axis, } public class RotateObject : MonoBehaviour { public Transform target; public bool isRot;//是否可以旋转 public float maxAngle=Mathf.Infinity;//旋转过的最大角度 public float minAngle=-Mathf.Infinity;//同上 public RotateEnum myRotEnum; public float roteSpeed=5f;//旋转速度 public bool isneedClamp=false;//是否需要设置角度限制 public float hasrotAngles;//用这个值来代表已经旋转过的角度,方便使用和判定 private Vector3 mousePos;//记录鼠标上一帧的位置 void Start() { //也可以委托添加事件 } void Update() { //可以使用射线检测的方法来实现旋转, } //设置需要旋转的对象 public void SetTarget (Transform go) { this.target = go; mousePos = Input.mousePosition; } //旋转 public void RotTarget() { if (isRot) { Vector3 offset = Input.mousePosition- mousePos; Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(target.position); //先将物体的世界坐标转换到屏幕坐标,主要是求将屏幕坐标转为世界坐标时对应的z值 Vector3 mouseWolrd = Camera.main.ScreenToWorldPoint (new Vector3( mousePos.x, mousePos.y, ScreenSpace.z));//鼠标上一帧的在屏幕上的位置转到世界坐标 Vector3 mouseWolrd1 = Camera.main.ScreenToWorldPoint (new Vector3( Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z));//当前帧的世界坐标 Vector3 dir2 = target.position - mouseWolrd; //计算物体只想鼠标的方向向量 Vector3 offset1 = mouseWolrd1- mouseWolrd;//计算鼠标指向的方向向量 Vector3 direction = Vector3.Cross (offset1, dir2);//计算叉乘值,用来判断鼠标移动的方向 switch (myRotEnum) { case RotateEnum.x_Axis: if (direction.x > 0) { hasrotAngles += Mathf.Abs (offset1.x) * roteSpeed; } else { hasrotAngles += -1f * Mathf.Abs (offset1.x) * roteSpeed; } if(isneedClamp) hasrotAngles = Mathf.Clamp (hasrotAngles, minAngle, maxAngle); target.localEulerAngles = new Vector3 ( hasrotAngles,target.localEulerAngles.y, target.localEulerAngles.z); break; case RotateEnum.y_Axis: if (direction.y > 0) { hasrotAngles += Mathf.Abs (offset1.y) * roteSpeed; } else { hasrotAngles += -1f * Mathf.Abs (offset1.y) * roteSpeed; } if(isneedClamp) hasrotAngles = Mathf.Clamp (hasrotAngles, minAngle, maxAngle); target.localEulerAngles = new Vector3 (target.localEulerAngles.x, hasrotAngles,target.localEulerAngles.z); break; case RotateEnum.z_Axis: if (direction.z > 0) { hasrotAngles += Mathf.Abs (offset1.z) * roteSpeed; } else { hasrotAngles += -1f * Mathf.Abs (offset1.z) * roteSpeed; } if(isneedClamp) hasrotAngles = Mathf.Clamp (hasrotAngles, minAngle, maxAngle); target.localEulerAngles = new Vector3 (target.localEulerAngles.x, target.localEulerAngles.y, hasrotAngles); break; default: break; } mousePos = Input.mousePosition; //重新赋值 } } }
如果有什么问题 ,大家多多指正