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     }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM