目录
前言:
基于拖拽接口的:
基于鼠标点击:
触摸点滑动:
前言:
物体旋转是绕Y轴旋转
以下这些方法都适应于触摸屏
基于拖拽接口的:
适用于UI,脚本应该挂载在能检测射线的UI相关的组件上,例如:可以是canvas或者相关的ui组件下
适用场景:在一定范围内滑动,可旋转3D物体
using UnityEngine; using UnityEngine.EventSystems; ////// /// * Writer:June /// /// * Data:2021.6.21 /// /// * Function:拖拽3D物体 /// /// * Remarks: /// /// public class Drag3DObject : MonoBehaviour, IDragHandler, IBeginDragHandler { ////// 目标模型 /// public GameObject tarGetObj; ////// 当前帧所在位置 /// private Vector2 currentPos; ////// 上一帧所在位置 /// private Vector2 lastPos; ////// 旋转速度 /// [Range(5, 50)] public float rotateSpeed = 15; public void OnBeginDrag(PointerEventData eventData) { lastPos = eventData.position; } public void OnDrag(PointerEventData eventData) { currentPos = eventData.position; tarGetObj.transform.Rotate(Vector3.up, (lastPos.x - currentPos.x) * Time.deltaTime * rotateSpeed); lastPos = eventData.position; } }
或
using UnityEngine; using UnityEngine.EventSystems; ////// /// * Writer:June /// /// * Data:2021.6.21 /// /// * Function:拖拽3D物体 /// /// * Remarks: /// /// public class Drag3DObject1 : MonoBehaviour, IDragHandler { ////// 目标模型 /// public GameObject tarGetObj; public void OnDrag(PointerEventData eventData) { tarGetObj.transform.localEulerAngles += new Vector3(0, -eventData.delta.x, 0); } }
基于鼠标点击:
全局适用,不管程序在干嘛,滑动屏幕就会触发
using UnityEngine; ////// /// * Writer:June /// /// * Data:2021.6.21 /// /// * Function:鼠标点击旋转 /// /// * Remarks: /// /// public class MouseOnClickRotate : MonoBehaviour { ////// 目标模型 /// public GameObject tarGetObj; ////// 当前帧所在位置 /// private Vector2 currentPos; ////// 上一帧所在位置 /// private Vector2 lastPos; ////// 旋转速度 /// [Range(5, 50)] public float rotateSpeed = 15; private void Update() { if (Input.GetMouseButtonDown(0)) { lastPos = Input.mousePosition; } if (Input.GetMouseButton(0)) { currentPos = Input.mousePosition; tarGetObj.transform.Rotate(Vector3.up, (lastPos.x - currentPos.x) * Time.deltaTime * rotateSpeed); lastPos = Input.mousePosition; } } }
触摸点滑动:
只适用于触摸屏,鼠标测试是没有效果的
using UnityEngine; ////// /// * Writer:June /// /// * Data:2021.6.22 /// /// * Function:触摸点控制旋转 /// /// * Remarks:鼠标测试不了,只能用于触摸屏,或者安卓 /// /// public class TouchRotate : MonoBehaviour { ////// 目标物体 /// public GameObject targetObject; ////// 旋转速度 /// public float rotateSpeed; private void Update() { if (Input.touchCount >= 1) { if (Input.GetTouch(0).phase == TouchPhase.Moved) { float moveX = Input.GetTouch(0).deltaPosition.x; targetObject.transform.Rotate(moveX * -rotateSpeed * Time.deltaTime * Vector3.up); } } } }



