TDでも作ろうかと思い、とりあえず書いてみた「上下左右にルートをたどらせる」プログラムです。
目的地を指定し、順番に目的地をたどらせることで道なりに動かします。
成果物

こんな感じで動きます。
//Unity C#
public class EnemyMovement : MonoBehaviour
{
//進行度
int enemyPosition = 0;
//目的地
List enemyAim = new List<Vector3>();
//進行方向
string goTo;
//方向転換フラグ
bool moveOver = true;
//速度
float enemySpeed = 3f;
void Start()
{
//初期位置
enemyAim.Add(new Vector3(5, 3, 0));
this.transform.position = enemyAim[enemyPosition];
//目的地
enemyAim.Add(new Vector3(4, 3, 0));
enemyAim.Add(new Vector3(4, 1, 0));
enemyAim.Add(new Vector3(2, 1, 0));
enemyAim.Add(new Vector3(2, 3, 0));
enemyAim.Add(new Vector3(4, 3, 0));
enemyAim.Add(new Vector3(4, -1, 0));
}
void FixedUpdate()
{
//方向
switch (goTo)
{
case "左":
this.transform.Translate(-0.01f * enemySpeed, 0, 0);
if (this.transform.position.x < enemyAim[enemyPosition].x)
{
moveOver = true;
}
break;
case "右":
this.transform.Translate(0.01f * enemySpeed, 0, 0);
if (this.transform.position.x > enemyAim[enemyPosition].x)
{
moveOver = true;
}
break;
case "下":
this.transform.Translate(0, -0.01f * enemySpeed, 0);
if (this.transform.position.y < enemyAim[enemyPosition].y)
{
moveOver = true;
}
break;
case "上":
this.transform.Translate(0, 0.01f * enemySpeed, 0);
if (this.transform.position.y > enemyAim[enemyPosition].y)
{
moveOver = true;
}
break;
}
if (moveOver)
{
//現在地とこれまでの目的地を一致させる
this.transform.position = enemyAim[enemyPosition];
//次の目的地を指定
enemyPosition++;
//目的地のxが現在地のxより小さい場合、進行方向は左
if (this.transform.position.x > enemyAim[enemyPosition].x)
{
goTo = "左";
}
//目的地のxが現在地のxより大きい場合、進行方向は右
else if (this.transform.position.x < enemyAim[enemyPosition].x)
{
goTo = "右";
}
//目的地のyが現在地のyより小さい場合、進行方向は下
else if (this.transform.position.y > enemyAim[enemyPosition].y)
{
goTo = "下";
}
//目的地のyが現在地のyより大きい場合、進行方向は上
else if (this.transform.position.y < enemyAim[enemyPosition].y)
{
goTo = "上";
}
moveOver = false;
}
}
}
使い方

上のコードを動かしたいオブジェクトにアタッチし、初期位置および移動したい座標を順々に指定します。オブジェクトは起動時に自動で初期位置へワープし、そこから移動を開始します。
座標は1で1マス基準で書いてます。
座標は1で1マス基準で書いてます。

「速度」を変えることで、移動スピードを変更できます。
コードの流れ

変数enemyPositionは「何回折れ曲がったか」を意味し、初期値は0です。
動的配列のenemyAimは複数のVector3を保存し、enemyPositionをインデックスとして使用することで、折れ曲がるたびに次の目的地を指定します。
動的配列のenemyAimは複数のVector3を保存し、enemyPositionをインデックスとして使用することで、折れ曲がるたびに次の目的地を指定します。

enemyAim.Addで配列enemyAimにVector3を追加していますが、最初に追加したVector3はenemyAim[0]、次に追加したものはenemyAim[1]として保管されています。この数字の代わりに「折れ曲がった回数」を使っているという理屈です。

方向転換フラグmoveOverがtrueになったタイミングで、次の目的地への目標設定がなされると同時に、向かう方向が指定されます。
オブジェクトは上下左右にしか動けないので、次の目的地(enemyAim[enemyPosition])のxが現在地のxより大きい=右にある場合進む方向は右になるし、yが現在地のyより小さい=下にあるなら、進むべき方向は下です。
条件で判別し、進行先を変数goToに代入します。
オブジェクトは上下左右にしか動けないので、次の目的地(enemyAim[enemyPosition])のxが現在地のxより大きい=右にある場合進む方向は右になるし、yが現在地のyより小さい=下にあるなら、進むべき方向は下です。
条件で判別し、進行先を変数goToに代入します。

進行方向へFixedUpdateでオブジェクトを移動させ、目的地を追い越した時点でオブジェクトの現在地を目的地と一致させます。
それからまたフラグmoveOverをtrueにし、次の目的地と進行方向を計算します。
それからまたフラグmoveOverをtrueにし、次の目的地と進行方向を計算します。

やりたいことから逆引きするUNITYの使い方まとめ
Unityをやりたいことから学習していけるよう、機能・用途別にまとめたページです。C#の命令別の逆引きは現時点で作っていません。2019の時期に書き始めているので、それより前のバージョンについては言及しません。
コメント