68 lines
2.8 KiB
C#
68 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Grid;
|
|
using UnityEngine;
|
|
|
|
namespace Actions {
|
|
public class MoveAction : BaseAction {
|
|
private const float moveSpeed = 4f;
|
|
private const float rotationSpeed = 10f;
|
|
private const float stoppingDistance = 0.1f;
|
|
private static readonly int isWalking = Animator.StringToHash("IsWalking");
|
|
[SerializeField] private Animator UnitAnimator;
|
|
[SerializeField] private int MaxMoveDistance = 4;
|
|
private Vector3 TargetPosition { get; set; }
|
|
|
|
protected override void Awake() {
|
|
base.Awake();
|
|
TargetPosition = transform.position;
|
|
}
|
|
|
|
private void Update() {
|
|
if (!IsActive) return;
|
|
|
|
Vector3 moveDirection = (TargetPosition - transform.position).normalized;
|
|
|
|
if (Vector3.Distance(TargetPosition, transform.position) > stoppingDistance) {
|
|
transform.position += moveSpeed * Time.deltaTime * moveDirection;
|
|
UnitAnimator.SetBool(isWalking, true);
|
|
}
|
|
else {
|
|
UnitAnimator.SetBool(isWalking, false);
|
|
IsActive = false;
|
|
OnActionComplete();
|
|
}
|
|
|
|
transform.forward = Vector3.Lerp(transform.forward, moveDirection, rotationSpeed * Time.deltaTime);
|
|
}
|
|
|
|
public override string GetActionName() => "Move";
|
|
|
|
public bool IsValidActionGridPosition(GridPosition gridPosition) => GetValidActionGridPositionList().Contains(gridPosition);
|
|
|
|
public 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 void Move(GridPosition gridPosition, Action onMoveCompleted) {
|
|
OnActionComplete = onMoveCompleted;
|
|
TargetPosition = LevelGrid.Instance.GetWorldPosition(gridPosition);
|
|
IsActive = true;
|
|
}
|
|
}
|
|
} |