Unity3D 一句话实现拖动鼠标使Cube旋转

通过本文,你将学会如何使用一句代码实现鼠标拖动使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,鼠标拖动、物体旋转

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容