1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

簡単なパス移動の実装

Last updated at Posted at 2019-09-21

ある地点とある地点を行き来するようなアルゴリズムを実装していきたい思います。

下準備

以下に出てくるVector3はこんな感じです(+とか=は省きます)。

Vector3.h
//ベクトルクラス
class Vector3 {
public:
float Length();   //ベクトルの長さを取得
void Normalize(); //ベクトルを正規化
float x;          //x
float y;          //y
float z;          //z
};

まず、ある地点を表すポイント構造体を作ります。

struct Point {
Vector3 s_position;   //ポイントの座標
int     s_number;     //ポイントの番号
};

それの配列とポインタをパス移動させたいクラスに持たせます。

Enemy.h
class Enemy {
std::vector<Point>   m_pointList;  //ポイント構造体の配列
Point*               m_point;      //ポイント構造体のポインタ、現在の目的地
                                   //となるポイント
    .
    .
    .
Vector3              m_position    //Enemyの座標
};

ポイントを設置します。

Enemy.cpp
m_pointList.push_back({Vector3(0.0f,0.0f,0.0f),1});     //一番目のポイント
m_pointList.push_back({Vector3(0.0f,100.0f,0.0f),2});   //二番目のポイント
m_pointList.push_back({Vector3(100.0f,0.0f,0.0f),3});   //三番目のポイント
m_pointList.push_back({Vector3(0.0f,0.0f,100.0f),4});   //四番目のポイント
m_point = &m_pointList[0];                              //一番目のポイントを入れる

パス移動

Enemy.cpp
//以下ループ

//目標とするポイントの座標から現在の座標を引いて、距離ベクトルを求める     
Vector3 diff = m_point->s_poition - m_position;
//距離が一定以内なら目的地とするポイントを変える
if(diff.Length() <= 20.0f) {

    //今目的地としているポイントが配列の最後の要素なら
  //一番最初のポイントを目的地とする
    if(m_point->s_number == m_poinstList.size()) {
        m_point = m_pointList[0];
    }

    //そうでないなら配列の次の要素のポイントを目的地とする
    else {
    m_point = m_pointList[m_point->s_number];
    }
}

//目標とするポイントの座標から現在の座標を引いて、距離ベクトルを求める 
Vector3 moveSpeed = m_point->s_position - m_position;
//正規化する
moveSpeed.Normalize();
//適当にスカラーをかける
moveSpeed *= 3.0f;  
//座標に加算する
m_position += moveSpeed;
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?