//Unity3D获取两个GameObject间距
var a : GameObject;
var b : GameObject;
//a,b分别定义两个公共GameObject对象
function Update() {
//如果a或者是b实例化失败就跳出函数
if ( a == null || b == null) {
print(" a or b = null");
return;
}
//注解一:私有,公有变量的问题
//m,n定义两个私有Vector3类型
var m : Vector3;
var n : Vector3;
//赋m,n予a,b的位置
m = a.transform.position;
n = b.transform.position;
//注解二:
//函数Vector3.Distance计算a,b间距,并在控制台输出
print(Vector3.Distance(m,n));
}
注解一:关于JavaScript的一些语法注意,请关注文章《JavaScript中的公有成员,私有成员和静态成员》。
注解二:Vector3.Distance(距离)
函数原型:
static function Distance (a : Vector3, b : Vector3) : float
Description(描述)
Returns the distance between a and b.
返回a和b之间的距离。
Vector3.Distance(a,b) is the same as (a-b).magnitude
Vector3.Distance(a,b) 等同于(a-b).magnitude 。
实例(C#):
using UnityEngine;
using System.Collections;
public class Distance01 : MonoBehaviour {
public Transform other;
public void Awake(){
//if(typeof(other)){ //报错:Distance01.other此处是字段,但被当作"类型"来使用
if (other)
{
float dist = Vector3.Distance(other.position,transform.position);
print("Distance to other:" + dist);
}
}
}
实例(JavaScript)
var other : Transform;
if (other) {
var dist = Vector3.Distance(other.position, transform.position);
print ("Distance to other: " + dist);
}