9
8

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.

GameAIの勉強がてらUnityを使って敵を追跡するアルゴリズムを実装してみた。

LOS追跡、Line-of-Sighは的に対して最短距離で追い込むようなものです。
仕組みは非常に簡単でプレイヤーとのVectorの差分を計算し、その方向に力を加えるだけです。

実際のコードはこんな感じ。

using UnityEngine;
using System.Collections; 

public class LosEnemyControlScript : MonoBehaviour {
    //追跡対象
    public GameObject objTarget;

    //今までいた位置を保持
    public Vector2 prev; 

    //初期化処理
    void Start () {
        prev = transform.position;
    }

    void Update () {
        Move(); 
    }

    //移動関数
    void Move(){
        //ユーザの場所を特定
        Vector2 Predetor = objTarget.transform.position;

        float x = Predetor.x;
        float y = Predetor.y;
        //追跡方向の決定
        Vector2 direction = new Vector2(x - transform.position.x, y - transform.position.y).normalized;
        //ターゲット方向に力を加える
        GetComponent<Rigidbody2D> ().velocity = (direction * 4);

        //本体の向きを調整
        Vector2 Position = transform.position;  
        Vector2 diff = Position - prev;
        if (diff.magnitude > 0.01) {
            float angle = Mathf.Atan2 (diff.y, diff.x) * Mathf.Rad2Deg - 90;
            transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
        } 
        //次回角度計算のために現在位置を保持
        prev = Position;
    }
}

これを動かすとこんな感じになります。
LOS追跡

かわいらしいですね♪

9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?