Unity 5.3 将物体转向鼠标所在位置

一、需求描述:

初始情况——

目标需求:

 

二、代码

 1     void Update () {
 2         // 获取鼠标位置相对移动向量
 3         Vector2 translation = new Vector2(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical"));
 4         // 根据鼠标位置相对移动向量移动物体
 5         transform.Translate(translation * speed * Time.deltaTime);
 6         // 当鼠标左键按下时
 7         if (Input.GetMouseButton(0))
 8         {
 9             // 鼠标坐标默认是屏幕坐标,首先要转换到世界坐标
10             // 物体坐标默认就是世界坐标
11             // 两者取差得到方向向量
12             Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
13             // 方向向量转换为角度值
14             float angle =360-Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
15             // 将当前物体的角度设置为对应角度
16             transform.eulerAngles = new Vector3(0, 0, angle);
17         }
18         
19     }

 

posted @ 2016-10-16 20:41  hercMoray  阅读(5190)  评论(0编辑  收藏  举报