查看: 1087|回复: 0
打印 上一主题 下一主题

[其他] unity中关于鼠标控制问题(比如控制球杆绕奈转动)

[复制链接]
may    

8830

主题

80

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
52312
精华
343

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2014-8-31 16:34:51 |只看该作者 |倒序浏览
控制球杆绕奈转动,首先能想到的恐怕是RotateAround吧,用这个方法先得计算出偏移角度、转动方向,然后再插值旋转。今天发现的新方法是利用Plane和射线做旋转:首先在目标物体的位置初始一个Plane,再用屏幕射线获得与Plane的交点,用交点和目标位置所得的向量,确定旋转。
代码记录:

  1. void Start()
  2.     {
  3.         mPlane = new Plane(Vector3.up, transform.position);
  4.     }
复制代码
  1. void Update()
  2.     {
  3.         if (Input.GetMouseButton(0))
  4.         {
  5.             Vector3 mousePos = Input.mousePosition;
  6.             Vector3 targetPos = InterSectionPoint(mPlane, mousePos, Camera.main);

  7.             Vector3 dirction = transform.position - targetPos;
  8.             float dist = dirction.magnitude;

  9.             if (dirction != Vector3.zero)
  10.             {
  11.                 arrow.rotation = Quaternion.LookRotation(dirction);
  12.             }
  13.             else
  14.             {
  15.                 arrow.LookAt(transform);
  16.             }}
  17. }
复制代码

  1. /// <summary>
  2.     /// 获得射线与平面交点
  3.     /// </summary>
  4.     /// <param name="plane"></param>
  5.     /// <param name="screenPoint"></param>
  6.     /// <param name="cam"></param>
  7.     /// <returns></returns>
  8.     Vector3 InterSectionPoint(Plane plane, Vector3 screenPoint,Camera cam)
  9.     {
  10.         Vector3 point = Vector3.zero;
  11.         float dist;
  12.         Ray ray = cam.ScreenPointToRay(screenPoint);
  13.         plane.Raycast(ray, out dist);

  14.         return ray.GetPoint(dist);
  15.     }
复制代码



分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

关闭

站长推荐上一条 /1 下一条

手机版|纳金网 ( 闽ICP备08008928号

GMT+8, 2024-5-15 19:41 , Processed in 0.085736 second(s), 33 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部