纳金网

标题: unity中关于鼠标控制问题(比如控制球杆绕奈转动) [打印本页]

作者: may    时间: 2014-8-31 16:34
标题: unity中关于鼠标控制问题(比如控制球杆绕奈转动)
控制球杆绕奈转动,首先能想到的恐怕是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.     }
复制代码








欢迎光临 纳金网 (http://c-www.narkii.com/club/) Powered by Discuz! X2.5