我要测量两个对象之间的距离

时间:2019-06-15 17:26:50

标签: c# unity3d

我想测量两个对象的距离(仅在Z轴上),如果这些对象的距离为= 50,则可以执行一些操作...但是我不能减去两个Vector3。

类似这样的东西:

 Vector3 Bullet;
 Vector3 player;
 public Vector3 distance;

 Bullet = new Vector3(0f, 0f, transform.position.z);
 Player = new Vector3(0f, 0f, player.position.z);

 if (distance = Bullet - Player)
 {
 Debug.Log("out of range");
 }

3 个答案:

答案 0 :(得分:2)

使用Vector3.Distance。

 Vector3 bullet = new Vector3(0f, 0f, player.position.z);;
 Vector3 player = new Vector3(0f, 0f, transform.position.z);
 public float distance;


    if (distance >= Vector3.Distance(other.position, transform.position))
     {
      print("out of range: " + dist);
     }

来源:https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

或者您可以直接减去z值。如果仅计算z值,则无需使用向量函数。

答案 1 :(得分:1)

如果仅需要使用Z轴,则根本不需要额外的向量。

您可以像这样计算一个轴上的距离:

Mathf.Abs(transform.position.z - player.position.z);

还要检查“超出范围”,您需要使用“> =”而不是“ ==”来避免错误,例如,在一帧中您的距离可能从49.9跳到51.1并用“ ==”在这种情况下将失败。

因此最终代码应为:

public Vector3 distance;

if (Mathf.Abs(transform.position.z - player.position.z) >= distance)
{
    Debug.Log("out of range");
}

答案 2 :(得分:0)

这不是您所需要的减法,只需计算两个向量3之间的距离即可

const v3Obj1 = { x: 10, y: 10, z: 75 }
const v3Obj2 = { x: -10, y: 15, z: 75 }

function distance(x0, y0, z0, x1, y1, z1) {
  let deltaX = x1 - x0
  let deltaY = y1 - y0
  let deltaZ = z1 - z0
  let distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ)
  return parseFloat(distance)
}

console.log(
  distance(v3Obj1.x, v3Obj1.y, v3Obj1.z, v3Obj2.x, v3Obj2.y, v3Obj2.z)
) // return {Float} 20.615528128088304

//经过测试的代码