由于是在屏幕内跟随鼠标移动,我们知道,在屏幕上鼠标位置的Z坐标的值为0,所以我们要将物体的位置坐标Z赋值给鼠标的Z;
1 using UnityEngine;
2 using System.Collections;
3
4 public class Follow: MonoBehaviour {
5 Vector3 world;//物体要移动到的位置 (世界坐标系)
6 float moveSpeed=0;//物体移动速度
7
8 void Update(){
9 Vector3 targetposition=Camera.main.WorldToScreenPoint(this.transform.position);//将物体的世界坐标转狗刨学习网换为屏幕坐标
10
11 Vector3 mouseposition=Input.mousePosition;//鼠标在屏幕上的位置坐标
12
13 if(Input.GetMouseButton(0)){
14 mouseposition.z=targetposition.z;
15
16 //world=Camera.main.ScreenToWorldPoint(mouse position);//这种情况下 会有穿透现象
17
18 world.x=Camera.main.ScreenToWorldPoint(mouse position).x;
19 world.z=Camera.main.ScreenToWorldPoint(mouse position).z;
20 world.y=this.transform.postion.y;
21
22 moveSpeed=3;
23 }
24
25 if(this.transform.position==world){//如果物体移动到了鼠标指定的位置 将移动速度设为0
26 moveSpeed=0;
27 }
28
29 this.transform.LookAt(world);//物体朝向鼠标对应的位置 (此时的位置为世界坐标系)
30 this.transform.Translate(Vector3.forward*moveSpeed*Time.deltaTime);
31 }
32 }
因篇幅问题不能全部显示,请点此查看更多更全内容