Unity3d--根据鼠标点击的位置改变物体朝向

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 /*
 5  * 根据鼠标点击位置改变物体朝向
 6 */
 7 public class PlayDir : MonoBehaviour {
 8 
 9     public GameObject effect;
10     private bool isMoving = false; //鼠标左键状态
11     private Vector3 targetPosition;
12 
13     // Update is called once per frame
14     void Update () {
15         //判断鼠标左键是否按下
16         if (Input.GetMouseButtonDown(0)) {
17             //获取由主摄像机位置到鼠标点击位置的一条射线
18             Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
19             RaycastHit hitInfo;
20             bool isCollider = Physics.Raycast (ray, out hitInfo);
21             //判断射线是否成功发射且是否触发目标物体
22             if (isCollider && hitInfo.collider.tag == Tags.ground) {
23                 //参数为目标物体的位置信息
24                 ShowClickEffect (hitInfo.point);
25                 isMoving = true;
26                 LookAtTarget (hitInfo.point);
27             }
28         }
29 
30         //判断鼠标左键是否抬起
31         if (Input.GetMouseButtonUp(0)) {
32             isMoving = false;
33         }
34 
35         if (isMoving) {
36             //获取由主摄像机位置到鼠标点击位置的一条射线
37             Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
38             RaycastHit hitInfo;
39             bool isCollider = Physics.Raycast (ray, out hitInfo);
40             //判断射线是否成功发射且是否触发目标物体
41             if (isCollider && hitInfo.collider.tag == Tags.ground) {
42                 LookAtTarget (hitInfo.point);
43             }
44         }
45     }
46 
47     void ShowClickEffect(Vector3 hitPoint){
48         hitPoint = new Vector3 (hitPoint.x, hitPoint.y + 0.3f, hitPoint.z);
49         GameObject.Instantiate (effect, hitPoint, Quaternion.identity);
50     }
51         
52     void LookAtTarget(Vector3 hitPoint){
53         //获取触发目标物体的位置信息
54         targetPosition = hitPoint;
55         //将目标位置的y轴修改为当前物体的y轴
56         targetPosition = new Vector3 (targetPosition.x, transform.position.y, targetPosition.z);
57 
58         //当前物体朝向目标位置
59         this.transform.LookAt (targetPosition);
60     }
61 }
posted @ 2016-06-16 14:29  yuge790615  阅读(2169)  评论(0编辑  收藏  举报