概要
敵機能の実装を行います。
今回は敵が初期位置に移動し待機する機能を実装します。
以下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
Section4 13
github コミット分
章まとめ