当前位置: 移动技术网 > IT编程>开发语言>c# > Unity3D实现鼠标控制旋转转盘

Unity3D实现鼠标控制旋转转盘

2019年07月18日  | 移动技术网IT编程  | 我要评论

在培训模拟考试软件中,我们经常会遇到类似用鼠标旋转转盘打开开关的需求。让用户更加真实的操作设备仪器。接下来说下我的解决方案。

因为鼠标操作是在ui平面上,所以我们要先将被操作的模型的世界坐标转换到屏幕坐标上。代码如下:

modelscreenpos = camera.worldtoscreenpoint(model.transform.position);

这里有个声明,这个模型代表的是转盘,而且要保证模型的中心点在转盘中心。然后我们就要计算鼠标以模型在屏幕坐标为中心点的旋转偏移量。我们开始以鼠标按下的瞬间,偏移量为0,然后进行每帧计算偏移量。偏移量也就是旋转角度,很好计算,就是求两个向量的夹角。角度angle=vector2.angle(oa,ob);

接下来我们要解决的就是旋转方向是顺时针还是逆时针的。利用unity的四元数公式

q = quaternion.fromtorotation(oa, ob);

得出的四元数我们可以根据四元数的z值判断旋转方向是顺时针还是逆时针的。当z为正时就是逆时针旋转,当为负时就是顺时针啦。可以自己写个向量xy平面向量旋转测试下。然后我们设置模型旋转轴对应的欧拉角分量加上我们获得的旋转角度。功能就实现了。思路大体是这样,但是在实现过程中有很多小的设置需要注意下。下面是我的源代码:

private vector2 modelpos;
  private vector2 mousepos; //当前鼠标位置
  private vector2 premousepos;//上一帧鼠标位置
  private quaternion q; 
  private float rotateangle;
  private vector3 localeluer; //模型欧拉角存储变量
 
  private bool isselect = false;
  void start()
  {
    modelpos = camera.worldtoscreenpoint(go.transform.position);
    angle = localeluer.x = info.opening;
    go.transform.localeulerangles = localeluer;
  }
 
  public virtual void update()
  {
    if (input.getmousebuttondown(0)&&modelcamera.istouch())
    {
      isselect = true;
      premousepos = mousepos=input.mouseposition; //每次重新点击的时候都重置鼠标上一帧点击坐标
    }
    if (input.getmousebutton(0)&& isselect)
    {
      mousepos = input.mouseposition;
      rotateangle = vector2.angle(premousepos - modelpos, mousepos - modelpos);
      //debug.log("rotateangle+"+rotateangle);
      if (rotateangle == 0)
      {
        premousepos = mousepos;
      }
      else
      {
        q = quaternion.fromtorotation(premousepos - modelpos, mousepos - modelpos);
        float k = q.z > 0 ? 1 : -1;
        localeluer.x += k * rotateangle;
        //debug.log(localeluer.x);
        angle = localeluer.x = mathf.clamp(localeluer.x, 0, allowangle); //这里是项目需要 限制一下旋转圈数
        go.transform.localeulerangles = localeluer;
        premousepos = mousepos;
      }
    }
    if (input.getmousebuttonup(0))
    {
      isselect = false;
    }  
  }

效果图如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网