【流れ】
オブジェクトA(以下A)とオブジェクトB(以下B)を用意します。
分かりやすいようにAをSphere、BをCubeとします。
AにBを追いかけるスクリプトをアタッチします。
このスクリプトで、くだんのベクトルについての実装を行います。
また追いかけるオブジェクトをインスペクタから登録できるようにしておきます。
(処理を単純にするためです)
追いかける対象のオブジェクトとしてBを登録します。
あとは登録されたオブジェクトと自身との位置関係から、ベクトルの計算を行い、追いかける処理を実装します。
【調べもの】
Transform.rotation
Unity - (クォータニオン版)特定方向を向くように、向きを変更する
【いつか理解したい】
UnityのベクトルとQuaternionによる回転について
UnityでRotation(Quaternion)をうまく使いたい
AI開発&クォータニオン入門~3.敵キャラをプレイヤーに向かせる
コメントなし↓
public class chase : MonoBehaviour {
public Transform target;
public float speed = 0.1f;
private Vector3 vec;
void Start () {
//target = GameObject.Find("対象").transform;
}
void Update () {
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (target.position - transform.position), 0.3f);
transform.position += transform.forward * speed;
}
}
コメント入り↓
public class chase : MonoBehaviour {
public Transform target;//追いかける対象-オブジェクトをインスペクタから登録できるように
public float speed = 0.1f;//移動スピード
private Vector3 vec;
void Start () {
//target = GameObject.Find("対象").transform; インスペクタから登録するのでいらない
}
void Update () {
//targetの方に少しずつ向きが変わる
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (target.position - transform.position), 0.3f);
//targetに向かって進む
transform.position += transform.forward * speed;
}
}
Quaternion.LookRotation(ベクトルA - ベクトルB);
で、ベクトルBの地点から見て、ベクトルAの方向を取得することができる。少しずつ向きを変えたいので
Quaternion.Slerp(from, to, t);
を使う。fromからtoに方向がt時間で変わる。tの値が小さいと少しずつ、マックス1.0でいきなり(Quaternion.LookRotationと同じ)変わる。
toの部分にQuaternion.LookRotation(ベクトルA - ベクトルB)を入れる。
向きが変わったらtransform.forwardでオブジェクトが向いている方向(前面)のベクトルが取れる。ベクトルの大きさは普通に実数を掛け算することで変更できるので速度と掛けあわせてpositionに足していく。