I was wondering how well Vector3.Distance()
works with getting the target.position
if target is still null
to start with, so first thing I changed was moving my previous null
guard at the start of Update()
.
Then, depending on the distance of the player towards the target, I either stopped the movement or made a MoveTo()
call again (so if standing still and attacking, and the enemy moved out of range, the player would start to follow to keep in attack range).
Also, I added a small helper method to reset the target allowing the player to retreat from attacking (there was some mention about it at the end of the video, actually…)
private Mover mover;
private void Awake()
{
mover = GetComponent<Mover>();
}
private void Update()
{
if (null == target) return;
if (Vector3.Distance(transform.position, target.position) < weaponRange)
{
mover.StopMovement();
}
else
{
mover.MoveTo(target.position);
}
}
And of course the PlayerController
should switch back to moving away:
private bool InteractWithMovement()
{
if (Physics.Raycast(GetMouseRay(), out RaycastHit hitInfo))
{
if (Input.GetMouseButton(0))
{
mover.MoveTo(hitInfo.point);
fighter.ClearAttack();
}
return true;
}
return false;
}
Right now it feels like Mover
and Fighter
are too close to each other, so some refactoring will be in order, sooner or later…