LoginSignup
2
1

More than 1 year has passed since last update.

タワーデフェンスゲーム Unity 敵の機能 2/10 敵が経路に沿って移動する

Last updated at Posted at 2023-03-29

概要

前回の続きです。

今回はオブジェクトが経路に沿って移動する機能を実装します。
以下gifアニメは、オブジェクトが経路を沿って移動している様子です。

Enemy1222.gif

開発環境

IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10

実装のポイント

敵オブジェクトが移動予定地点に近づくと、次に移動する点が変更されます。
これを終点に達するまで繰り返すことで、敵オブジェクトは経路に沿って移動します。

敵オブジェクトが近づいたかどうかは、Vector3.Distanceメソッドを使って敵オブジェクトと到着予定地点の距離から判断します。距離の値が近づいた場合は「現在の要素数+1」をして次の点の座標に移動するようにします。

コード

Enemy.cs
using System;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 3f;
    [SerializeField] private Waypoint waypoint;
    public Vector3 CurrentPointPosition => waypoint.GetWaypointPosition(_currentWaypointIndex);
    private int _currentWaypointIndex;

    private void Start()
    {
        _currentWaypointIndex = 0;
    }

    private void Update()
    {
        Move();
+        if (CurrentPointPositionReached())
+        {
+            _currentWaypointIndex++;
+        }
    }

    private void Move()
    {
        Vector3 currentPosition = waypoint.GetWaypointPosition(_currentWaypointIndex);
        transform.position = Vector3.MoveTowards(transform.position, currentPosition, moveSpeed * Time.deltaTime);
    }
    
+    private bool CurrentPointPositionReached()
+    {
+        return Vector3.Distance(transform.position, CurrentPointPosition) < 0.1f;
+    }

}

参考

image.png

Section4 13

github コミット分

章まとめ

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