Unity鼠标控制物体拖拽旋转

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum ShowType
{
    None,
    Move,
    Rotate
}
public class Mousemove : Singleton
{
    public Transform Obj;//被操作的物体Obj
    public float sensitivity = 0.1f;//灵敏度
    public float rotate = 5f;//旋转速度
    private Vector3 mouseMoveDirection;
    private float mouseX;
    private float mouseY;
    public ShowType showtype;
    // Update is called once per frame
    private float maxYRotation = 120;
    private float minYRotation = 0;
    public bool IsStepClick = false;
    void Update()
    {
        if (IsStepClick)
        {
            switch (showtype)
            {
                case ShowType.None:
                    break;
                case ShowType.Move:
                    MouseMove();
                    break;
                case ShowType.Rotate:
                    MouseRotate();
                    break;
                default:
                    break;
            }
        }
    }
    void MouseMove()//鼠标左键使物体移动
    {
        mouseX = Input.GetAxis("Mouse X");
        if (Input.GetMouseButton(0))//鼠标左键
        {
            mouseMoveDirection = new Vector3(0, 0, -mouseX) * sensitivity;
            Obj.Translate(mouseMoveDirection, Space.Self);
        }
    }
    void MouseRotate()//鼠标右键使物体旋转
    {
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");
        if (Input.GetMouseButton(1))//鼠标右键
        {
            Debug.Log("旋转执行"+Obj.name+showtype+mouseX+mouseY);
            float xPosPrecent = Input.mousePosition.x / Screen.width;
            //鼠标在轴上旋转的角度
            float yAngle = Mathf.Clamp(xPosPrecent * maxYRotation, minYRotation, maxYRotation) - 60;
            Obj.transform.Rotate(Vector3.up, yAngle * rotate, Space.Self);
        }
    }
}

你可能感兴趣的:(unity)