unity 跟随鼠标 顺时针或逆时针旋转

private bool m_IsFirst = true;//用于记录第一帧按下鼠标时鼠标的位置,便于计算
    private Vector3 m_CurrentPos;//记录当前帧鼠标所在位置
    private bool m_IsClockwise;//是否顺时针
    private float m_RoundValue = 0;//记录总的旋转角度 用这个数值来控制一圈半
    public float Speed = 58.8f;//动画播放速度
    public GameObject Lingjian;//手轮零件
    public GameObject NiutouAnimator;//动画


    private void OnMouseDrag()
    {
        //从摄像机发出到点击坐标的射线
        Ray clickRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit clickPoint;


        if (Physics.Raycast(clickRay, out clickPoint))
        {
            //划出射线,只有在scene视图中才能看到
            Debug.DrawLine(clickRay.origin, clickPoint.point,Color.red);
            //划出射线,只有在scene视图中才能看到
            Vector3 pos;
            pos = clickPoint.point;//射线碰撞的点
            //点与手轮之间的向量坐标
            pos.x = pos.x - transform.position.x;
            pos.y = pos.y - transform.position.y;
            //计算后鼠标以方向盘圆心为坐标原点的坐标位置
            Vector3 pos3 = new Vector3(pos.x, pos.y, 0);


            //用于记录第一帧按下鼠标时鼠标的位置,便于计算
            if (m_IsFirst)
            {
                m_CurrentPos = pos3;
                m_IsFirst = false;
            }


            //计算当前帧和上一帧手指位置 用于判断旋转方向,在Unity3D中,Vector3.Dot表示求两个向量的点积;Vector3.Cross表示求两个向量的叉积。
            Vector3 currentPos = Vector3.Cross(pos3, m_CurrentPos);


            print("向量叉积" + currentPos);


            if (currentPos.z > 0)
            {
                //是否顺时针
                m_IsClockwise = true;
                // print(m_RoundValue);
                print("顺时针");
            }
            else if (currentPos.z < 0)
            {
                //是否顺时针
                m_IsClockwise = false;
                // print(m_RoundValue);
                print("逆时针");
            }


            if (m_CurrentPos != pos3)
            {
                //范围内让方向盘随着手指转动
                //顺时针
                if (m_IsClockwise)
                {
                    //记录总的旋转角度 用这个数值来控制一圈半
                    m_RoundValue += Vector3.Angle(m_CurrentPos, pos3);
                    //动画播放速度
                    //NiutouAnimator.GetComponent<Test_AnimSeek>().i = m_RoundValue / Speed;
                    transform.Rotate(new Vector3(0, 0, Vector3.Angle(m_CurrentPos, pos3)));
                }
                //逆时针
                else
                {
                    //记录总的旋转角度 用这个数值来控制一圈半
                    m_RoundValue -= Vector3.Angle(m_CurrentPos, pos3);
                    //动画播放速度
                    // NiutouAnimator.GetComponent<Test_AnimSeek>().i = m_RoundValue / Speed;
                    transform.Rotate(new Vector3(0, 0, -Vector3.Angle(m_CurrentPos, pos3)));
                }
            }
            m_CurrentPos = pos3;
        }
    }


    private void OnMouseUp()
    {
        m_IsFirst = true;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42399500/article/details/81017522