美文网首页
在unity中用鼠标控制控制物体旋转

在unity中用鼠标控制控制物体旋转

作者: xiaoxingyun | 来源:发表于2016-10-11 01:12 被阅读5770次

    功能大概是这个样子的,用鼠标的上下、左右移动来控制unity中某个物体的左右、上下转转。

        public  Camera cam;
        void Update()
        {
            Vector3 fwd = cam.transform.forward;
            fwd.Normalize();
            if (Input.GetMouseButton(0))
            {
                Vector3 vaxis = Vector3.Cross(fwd, Vector3.right);
                transform.Rotate(vaxis, -Input.GetAxis("Mouse X"), Space.World);
                Vector3 haxis = Vector3.Cross(fwd, Vector3.up);
                transform.Rotate(haxis, -Input.GetAxis("Mouse Y"), Space.World);
            }
        }
    
    

    transform.Rotate()这个函数官方是这样解释的:

    public void Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self); 
    axis           Axis to apply rotation to.
    angle          Degrees to rotation to apply.
    relativeTo     Rotation is local to object or World.
    

    因为物体在不断随着鼠标的运动旋转,所以旋转时一定要在世界坐标中,否则我们看到的是物体绕着自身的轴转转。另外,我们看到的都是通过camera来看到的,所以Rotate的第一个参数axis一定要是camera的某个轴向,左右方向的旋转需要绕着camera的up方向,上下方向的旋转需要绕着camera的right方向。
    这样无论物体和camera初始的rotation是多少,都可以正确的实现旋转啦。

    相关文章

      网友评论

          本文标题:在unity中用鼠标控制控制物体旋转

          本文链接:https://www.haomeiwen.com/subject/odivyttx.html