This episode deals with the fact that our player keeps running towards out CombatTarget even if we click somewhere else on the screen. The solution proposed in this Episode seem very inefficient and a round about way of doing it. But I am scared that if I do it another way that there is meaning behind the method chosen that i don’t see yet due to not knowing what is in future episodes.
This is the github repository for that episode if you need to review the solution suggested:
My Fighter.cs solution:
namespace Scripts.Combat
{
public class Fighter : MonoBehaviour
{
[SerializeField] float weaponRange = 2f;
Mover _mover;
Transform _targetTransform;
bool _hasCombatTarget = false;
void Start()
{
AssignVariables();
}
void AssignVariables()
{
_mover = GetComponent<Mover>();
}
void Update()
{
if (!_hasCombatTarget) return;
if (Vector3.Distance(_targetTransform.position, transform.position) > weaponRange)
{
_mover.MoveTo(_targetTransform.position);
}
else
{
_mover.StopMoving();
StopFollowingCombatTarget(); //optional, I prefer not to have continuous combat in a ARPG.
}
}
public void Attack(CombatTarget target)
{
_targetTransform = target.transform;
_hasCombatTarget = true;
}
public void StopFollowingCombatTarget()
{
_hasCombatTarget = false;
}
}
}
My InteractWithMovement method in PlayerController.cs that calls StopFollowingCombatTarget():
bool InteractWithMovement()
{
bool hasHit = Physics.Raycast(GetMouseRay(), out RaycastHit hit);
if (hasHit)
{
if (Input.GetMouseButton(0))
{
_mover.MoveTo(hit.point);
_fighter.StopFollowingCombatTarget(); //this is all
}
return true;
}
return false;
}
Not only do you not have to create separation inside the Mover script for no real reason, which is nice but not crucial, the most important part is that you are not doing a null compare in a Update() method which is just, well bad practice (if you don’t need to)? https://github.com/JetBrains/resharper-unity/wiki/Avoid-null-comparisons-against-UnityEngine.Object-subclasses
I am not posting to bash on the code he wrote, I am asking if there is any reason the way he wrote it is better than my way because (subjectively) I think my code is easier to understand and add less noise overall.