67 lines
2.7 KiB
C#
67 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Grid;
|
|
using UnityEngine;
|
|
using UnityEngine.Serialization;
|
|
|
|
namespace Actions {
|
|
public class MoveAction : BaseAction {
|
|
private const float moveSpeed = 4f;
|
|
private const float rotationSpeed = 10f;
|
|
private const float stoppingDistance = 0.1f;
|
|
[FormerlySerializedAs("MaxMoveDistance")] [SerializeField] private int maxMoveDistance = 4;
|
|
private Vector3 TargetPosition { get; set; }
|
|
|
|
public event EventHandler OnStartMoving;
|
|
public event EventHandler OnStopMoving;
|
|
|
|
|
|
protected override void Awake() {
|
|
base.Awake();
|
|
TargetPosition = transform.position;
|
|
}
|
|
|
|
private void Update() {
|
|
if (!IsActive) return;
|
|
|
|
Vector3 moveDirection = (TargetPosition - Unit.GetWorldPosition()).normalized;
|
|
|
|
if (Vector3.Distance(TargetPosition, Unit.GetWorldPosition()) > stoppingDistance) {
|
|
transform.position += moveSpeed * Time.deltaTime * moveDirection;
|
|
}
|
|
else {
|
|
ActionComplete();
|
|
OnStopMoving?.Invoke(this, EventArgs.Empty);
|
|
}
|
|
|
|
transform.forward = Vector3.Lerp(transform.forward, moveDirection, rotationSpeed * Time.deltaTime);
|
|
}
|
|
|
|
public override string GetActionName() => "Move";
|
|
|
|
public override List<GridPosition> GetValidActionGridPositionList() {
|
|
List<GridPosition> validGridPositionList = new();
|
|
GridPosition unitGridPosition = Unit.GridPosition;
|
|
for (int x = -maxMoveDistance; x <= maxMoveDistance; x++) {
|
|
for (int z = -maxMoveDistance; z <= maxMoveDistance; z++) {
|
|
GridPosition offsetGridPosition = new(x, z);
|
|
GridPosition testGridPosition = unitGridPosition + offsetGridPosition;
|
|
|
|
if (!LevelGrid.Instance.IsValidGridPosition(testGridPosition)) continue; //Only return valid grid positions
|
|
if (unitGridPosition == testGridPosition) continue; //Same grid position where the unit is already at
|
|
if (LevelGrid.Instance.HasAnyUnitOnGridPosition(testGridPosition)) continue; //Grid position already accopied with anther unit
|
|
|
|
validGridPositionList.Add(testGridPosition);
|
|
}
|
|
}
|
|
|
|
return validGridPositionList;
|
|
}
|
|
|
|
public override void TakeAction(GridPosition gridPosition, Action onMoveCompleted) {
|
|
ActionStart(onMoveCompleted);
|
|
TargetPosition = LevelGrid.Instance.GetWorldPosition(gridPosition);
|
|
OnStartMoving?.Invoke(this, EventArgs.Empty);
|
|
}
|
|
}
|
|
} |