通过本文,你将学会如何使用一句代码实现鼠标拖动使Cube旋转
效果预览:
代码如下
using UnityEngine;
public class RotateCube : MonoBehaviour
{
public float sensitive = 0.001f;
private void OnMouseDrag()
{
gameObject.transform.Rotate(new Vector3(0, (Input.mousePosition.x- Camera.main.WorldToScreenPoint(gameObject.transform.position).x)* sensitive, 0));
}
}
再来一份:
using UnityEngine;
public class RotateCube : MonoBehaviour
{
float value = 0f;
public float sensitive = 1.5f;
private void OnMouseDrag()
{
value += Input.GetAxis("Mouse X");
gameObject.transform.Rotate(new Vector3(0, value * sensitive, 0));
}
private void OnMouseUp()
{
value = 0f;
}
}
下面是笔者收藏的其他网友的方法:基本原理是将鼠标拖动的距离转换为物体旋转的角度
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
private Vector3 startPoint;
private Vector3 endPoint;
private int disToAngle=5;
void Update () {
if(Input.GetMouseButtonDown(0)){
startPoint=Input.mousePosition;
}
if(Input.GetMouseButton(0)){
endPoint=Input.mousePosition;
}
float dx=endPoint.x-startPoint.x;
float angle=dx/disToAngle;
this.transform.localEulerAngles=new Vector3(0,angle,0);
}
}
标签:Unity3D 、Cube 、Rotate、LocalEulerAngles,鼠标拖动、物体旋转