LoginSignup
1
1

More than 3 years have passed since last update.

【Unity】対象を追跡する

Last updated at Posted at 2020-08-22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// ずっと、追いかける
public class Forever_Chase : MonoBehaviour
{
    public string targetObjectName;   // 目標オブジェクト名
    public float speed = 1; // スピード:Inspectorで指定
    GameObject targetObject;

    void Start () // 最初に、目標オブジェクトを見つけておく
    {
        targetObject = GameObject.Find(targetObjectName);
    }

    private void FixedUpdate() // ずっと、目標オブジェクトの方向を調べて
    {
        Vector3 dir = (targetObject.transform.position - this.transform.position).normalized;
        // その方向へ指定した量で進む
        float vx = dir.x * speed;
        float vz = dir.z * speed;
        this.transform.Translate(vx / 50, 0,  vz / 50);
    }
}

まず下記で、追跡する対象の方向を求める
Vector3 dir = (targetObject.transform.position - this.transform.position).normalized;

そのあと、求めたx軸とz軸方向に、速度の値をかける。

ezgif.com-video-to-gif (2).gif

1
1
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
1