もし空間上の 1 点を別の点から引くと結果はひとつのオブジェクトからもうひとつを “指す” ベクトルとなります。
// Gets a vector that points from the player's position to the target's.
var heading = target.position - player.position;
ターゲットオブジェクトの方向を指すとともに、このベクトルの大きさは二つの位置の間の距離に等しくなります。一般的にはターゲットを向いた正規化されたベクトルが必要となります(発射物を向ける場合も同様)。オブジェクトの間の距離は向かっているベクトルと等しく、このベクトルを正規化するためには大きさで割ります:
var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.
大きさ (magnitude) と正規化されたプロパティの両方を別々に使用する場合、両方ともに CPU をかなり消費するため (両方とも平方根計算を含むため)、この方法がより望ましいと言えます。
もし比較のため距離だけが必要な場合 (例えば近接度合いのチェック) は、magnitude の計算をすべて回避できます。sqrMagnitude プロパティは、magnitude の値の 2 乗を求め、magnitude と同じように計算されますが、時間のかかる平方根演算は行われません。magnitude を既知の distance (距離) と比較するのではなく、magnitude の 2 乗を distance の 2 乗と比較できます。
if (heading.sqrMagnitude < maxRange * maxRange) {
// ターゲットは範囲内
}
これは真の大きさを比較で使用するよりも遥かに効率的です。
しばしば真上から見たターゲットへの向きが必要な場合があります。例えば、地面に立っている人が空中にういているターゲットに向かう必要がある場合を想像します。もし、プレイヤーの位置からターゲットの位置を引き算すると、結果のベクトルはターゲットに向かって上方向になります。これはプレイヤーの transform の向きを決めるには適切ではなく、プレイヤー自身も上向きに傾いてしまいます。実際に必要であるのはプレイヤーの位置からターゲットの真下の位置へのベクトルです。これは引き算した結果の Y 座標を 0 にすることで容易に得られます。
var heading = target.position - player.position;
heading.y = 0; // This is the overground heading.
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.