纳金网
标题:
判断两个物体之间的距离的代码
[打印本页]
作者:
王者再临
时间:
2014-12-31 21:34
标题:
判断两个物体之间的距离的代码
方法1
01var aa:GameObject;//A
02var bb:GameObject;//B
03var dis: float;
04function Update () {
05 dis=Vector3.Distance(bb.transform.position,aa.transform.position);
06}
07
08function OnGUI () {
09 GUI.Label (Rect (10,40,200,20), dis + “m”);
10}
复制代码
方法2
01var startPoint:Vector3;
02var endPoint:Vector3;
03var showDistance:float = 0.0;
04var isStart:boolean;
05var isOver:boolean;
06var isFollow:boolean;
07var mLine:LineRenderer;
08var aMaterial:Material;
09var mx:float = 0.0;
10var my:float = 0.0;
11
12function Start ()
13{
14 mLine = this.gameObject.AddComponent(LineRenderer);
15 mLine.SetWidth(1, 1);
16 mLine.SetVertexCount(2);
17 mLine.SetColors (Color.yellow,Color.yellow);
18 //aMaterial.color = Color.red;
19 mLine.material = aMaterial;
20 mLine.material.color = Color (0, 1, 0, 0.25);
21 mLine.renderer.enabled = true;
22}
23
24function Update () {
25//print(Input.mousePosition);
26if (Input.GetButtonDown (“Fire1”)) {
27 showDistance = 0;
28 startPoint = Vector3.zero;
29 endPoint = Vector3.zero;
30 isFollow = true;
31 var sRay = camera.ScreenPointToRay (Input.mousePosition);
32 var sHit : RaycastHit;
33 if (Physics.Raycast (sRay,sHit)) {
34 //Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
35 //Debug.DrawLine (sRay.origin, sHit.point);
36 startPoint = sHit.point;
37 print(“startPoint:” +sHit.point);
38 mLine.SetPosition(0,startPoint);
39 isStart = true;
40 isOver = false;
41 }else{
42 print(“”);
43 }
44}
45
46if(isStart && !isOver){
47 var mRay = camera.ScreenPointToRay (Input.mousePosition);
48 var mHit : RaycastHit;
49 if (Physics.Raycast (mRay,mHit)) {
50 endPoint = mHit.point;
51 print(“mPoint:” +mHit.point);
52 mLine.SetPosition(1,endPoint);
53 showDistance = Vector3.Distance(endPoint,startPoint);
54 }else{
55 print(“”);
56 }
57}
58
59if (Input.GetButtonUp (“Fire1”)) {
60 var eRay = camera.ScreenPointToRay (Input.mousePosition);
61 var eHit : RaycastHit;
62 isFollow = false;
63 if (Physics.Raycast(eRay,eHit)) {
64 //Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
65 //Debug.DrawLine (eRay.origin, eHit.point);
66 endPoint = eHit.point;
67 print(“endPoint:” +eHit.point);
68 isOver = true;
69 isStart = false;
70 showDistance = Vector3.Distance(endPoint,startPoint);
71 //Debug.DrawLine (startPoint,endPoint, Color.red);
72 mLine.SetPosition(1,endPoint);
73 }else{
74 print(“”);
75 }
76}
77}
78
79
80
81
82function OnGUI () {
83//GUI.TextArea (Rect (300, 80, 50, 20), showDistance.ToString());
84if(isFollow){
85 mx = Input.mousePosition.x + 5;
86 my = Screen.height-Input.mousePosition.y - 20;
87}
88GUI.Label(Rect (mx,my, 100, 20), showDistance.ToString() + “ M”);
89}
复制代码
欢迎光临 纳金网 (http://c-www.narkii.com/club/)
Powered by Discuz! X2.5