LoginSignup
1
1

More than 1 year has passed since last update.

タワーデフェンスゲーム Unity 敵の機能 1/10 初期時点に移動し待機するようにする

Last updated at Posted at 2023-03-28

概要

敵機能の実装を行います。
今回は敵が初期位置に移動し待機する機能を実装します。

以下gifアニメは 初期時点を動かしてオブジェクトがそれに追従している様子です。

Enemy1.gif

続き

開発環境

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

実装のポイント

Vector3.MoveTowardsメソッドを使って点の座標に敵オブジェクトが移動するようにします。
Waypointに該当する点を取得するメソッドを追加します。

コード部分

Waypoint.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

// 座標を定義しているクラス、オブジェクトにアタッチする
public class Waypoint : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] private Vector3[] points;
    public Vector3[] Points => points;

    void Start()
    {
    }
    private void OnDrawGizmos()
    {
        for (int i = 0; i < points.Length; i++)
        {
            if (i < points.Length - 1)
            {
                Gizmos.color = Color.yellow;
                // 隣接する2点間の距離を引く
                Gizmos.DrawLine(points[i], points[i + 1]);
            }
        }
    }

+    public Vector3 GetWaypointPosition(int index)
+    {
+        return points[index];
+    }
}
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 = 1;
    }

    private void Update()
    {
        Move();
    }

    private void Move()
    {
        Vector3 currentPosition = waypoint.GetWaypointPosition(_currentWaypointIndex);
        transform.position = Vector3.MoveTowards(transform.position, currentPosition, moveSpeed * Time.deltaTime);
    }
}

参考

Vector3.MoveTowards

image.png

Section4 13

github コミット分

章まとめ

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