LoginSignup
11
12

More than 5 years have passed since last update.

キャラクターの後ろを追尾してくるカメラの実装

Last updated at Posted at 2018-01-03

三人称視点のゲームでは、カメラがプレイヤーの後ろに回り込んでくる処理が、よく実装されています。

こんなやつ。

IMAGE ALT TEXT HERE

この処理の疑似コードを記載します。なお、3Dゲームを作るうえでの簡単なベクトルやカメラの知識はあるものとします。
肝は、新しい視点を決定する際に、元々の注視点と視点の距離を維持するように視点を決定することです。

/////////////////////////////////////////////////////////////////
// ⓵ 現在のカメラの注視点と視点を使って、XZ平面上での、
//      注視点から視点までのベクトル(toCameraPosXZ)と長さ(toCameraPosXZLen)を求める。
/////////////////////////////////////////////////////////////////
Vector3 toCameraPosXZ = m_camera.m_position - m_camera.m_target;
float height = toCameraPosXZ.y;                  //視点へのY方向の高さは、後で使うのでバックアップしておく。
toCameraPosXZ.y = 0.0f;                          //XZ平面にするので、Yは0にする。
float toCameraPosXZLen = toCameraPosXZ.Length(); //XZ平面上での視点と注視点の距離を求める。
toCameraPosXZ.Normalize();                       //単位ベクトル化。

/////////////////////////////////////////////////////////////////
// ⓶ 新しい注視点をアクターの座標から決める。
/////////////////////////////////////////////////////////////////
Vector3 target = m_actor->m_position;
target.y += 50.0f;

/////////////////////////////////////////////////////////////////
// ⓷ 新しい注視点と現在のカメラの視点を使って、XZ平面上での、
//     注視点から視点までのベクトル(toNewCameraPos)を求める。
/////////////////////////////////////////////////////////////////
Vector3 toNewCameraPos = m_camera.m_position - target; //新しい注視点からカメラの始点へ向かうベクトルを求める。
toNewCameraPos.y = 0.0f;              //XZ平面にするので、Yは0にする。
toNewCameraPos.Normalize();         //単位ベクトル化。

/////////////////////////////////////////////////////////////////
// ⓸ 1と2と3で求めた情報を使って、新しい視点を決定する。
/////////////////////////////////////////////////////////////////
//ちょっとづつ追尾。
float weight = 0.7f;  //このウェイトの値は0.0~1.0の値をとる。1.0に近づくほど追尾が強くなる。
toNewCameraPos = toNewCameraPos * weight + toCameraPosXZ * (1.0f - weight);
toNewCameraPos.Normalize();
toNewCameraPos *= toCameraPosXZLen; 
toNewCameraPos.y = height;              //高さを戻す。
Vector3 pos = target + toNewCameraPos;  //これで新しい視点が決定。

/////////////////////////////////////////////////////////////////
// ⓹ 視点と注視点をカメラに設定して終わり。
/////////////////////////////////////////////////////////////////
m_camera.m_position = pos;
m_camera.m_target = target;

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12