【Unity】追いかけてくる敵を作ってみる

2021/9/10ドラッグ処理の一部修正


ダンジョン系のゲームをやっていると、
ゾンビがひたすら追いかけてくるシーンがあります。
逃げても逃げても憑いてくる…
何ともやらしい演出なんですが

どうやって処理されているのか疑問に思ったので、
実際に作ってみようと思います。

ChaseTest①.jpg
android用のセッティングでAとBの2つのオブジェクトを用意します。

Aは青玉
Bは黒玉

Aを動かすとBが追いかけてくる感じにします。

Aはドラッグ操作できるように次のスクリプトをアタッチします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AScript : MonoBehaviour
{
private float ballPosZ; //青玉のZ座標

// Start is called before the first frame update
void Start()
{
ballPosZ = transform.position.z;
}

//ドラッグ処理
private void OnMouseDrag()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = ballPosZ;
transform.position = mousePos;
}
}

スクリプトをAオブジェクトにアタッチします。

青玉には、CircleCollider2DとRigidbody2Dを追加して、
Rigidbodyの設定は、
ボディタイプ キネマティック
完全なキネマティックコンタクトにチェックを入れます。
これで青玉はドラッグ操作できると思います。

続いて、Bオブジェクトですが、
Aオブジェクトを追いかけていくので、
Aの座標を取得して、そこへ移動する処理が必要になります。

まず、Aの座標取得から

public GameObject a;       //Aオブジェクト取得
private RectTransform atran; //Aオブジェクトのtransformを取得

void Start()
{
atran = a.GetComponent<RectTransform>();
}


これでAオブジェクトのtransformを取得できます。

続いて、移動処理なんですが、DoTweenを使います。
複雑な移動処理が簡単にできるので重宝しております(;^ω^)

まず、assetstoreからインポートします。
インポートについては、過去記事
DOTWeenを使って簡易Puzzleを作ってみる
を参照して下さい。


private RectTransform btaran; //Bオブジェクトのtransform取得

void Start()
{
btaran = this.gameObject.GetComponent<RectTransform>();
atran = a.GetComponent<RectTransform>();
}

//Aオブジェクトの座標へ移動する
void EnemyMove()
{
float x = atran.transform.localPosition.x;
float y = atran.transform.localPosition.y;

btaran.DOLocalMove(new Vector3(x,y,0), 2);
}


こんな感じでBオブジェクトは動きそうです。

後は、Aオブジェクトの位置を常に更新するので、
UpdateからEnemyMoveメソッドを呼び出せば、追いかけてくるように
なるかと思います。

最後に完成版のスクリプトを

BScript

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class BScript : MonoBehaviour
{

public GameObject a; //Aオブジェクト取得
private RectTransform atran; //Aオブジェクトのtransform取得

private RectTransform btaran; //Bオブジェクトのtransform取得

// Start is called before the first frame update
void Start()
{
btaran = this.gameObject.GetComponent<RectTransform>();
atran = a.GetComponent<RectTransform>();
}

// Update is called once per frame
void Update()
{
EnemyMove();
}

//Aオブジェクトの座標へ移動する
void EnemyMove()
{
float x = atran.transform.localPosition.x;
float y = atran.transform.localPosition.y;

btaran.DOLocalMove(new Vector3(x,y,0), 2);
}
}


このスクリプトをBオブジェクトにアタッチ、
変数aにAオブジェクトをアタッチしてプレイでっす。


DOLocalMove(new Vector3(x,y,0), 2);
移動時間を2秒にしましたが、この秒数をいじると
敵スピードが調整できます。


一応追いかけてくる状態は作れたのですが、
黒玉の数を増やすと重なってしまいます。

複数の敵がぞろぞろ追いかけてくる表現はうまく行きません。

調べてみるとnaviなるものがあるとか…
もう少し勉強が必要なようです。(T-T) グスッ

この記事へのコメント