如果从空间中的一个点减去另一个点,则得到的结果是从一个对象“指向”另一个对象的矢量:
// 获取从玩家位置指向目标位置的矢量。
var heading = target.position - player.position;
除了指向目标对象的方向之外,该矢量的大小等于两个位置之间的距离。通常需要归一化矢量来提供目标的方向以及到目标的距离(例如用于指挥飞弹)。对象之间的距离等于方向矢量的大小,该矢量可以通过除以其大小来归一化:
var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.
此方法优于单独使用大小和归一化属性,因为大小和归一化属性都非常耗费 CPU(都涉及计算平方根)。
如果只需要使用距离进行比较(例如,进行接近检查),则可以完全避免大小计算。sqrMagnitude 属性给出大小值的平方,计算方式与大小相似,但不需要进行耗时的平方根运算。不要将大小与已知距离进行比较,可将大小的平方与距离的平方进行比较:
if (heading.sqrMagnitude < maxRange * maxRange) {
// 目标在范围内。
}
这种算法比在比较中使用真实大小要高效得多。
有时,需要平行于地面的目标方向。例如,想象一个站在地面上的玩家需要接近漂浮在空中的目标。如果从目标位置减去玩家位置,那么产生的矢量将向上指向目标。这种情况下不适合对玩家变换进行定向,因为变换也会指向上方;真正需要的是从玩家位置到目标正下方地面位置的矢量。通过使用减法结果并将 Y 坐标设置为零,很容易获得该矢量:
var heading = target.position - player.position;
heading.y = 0; // 这是平行于地面的方向。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.