Hi Hugo, great course, I am learning a lot about code architecture this week!
I have a quick concern regarding how you are calculating the BulletProjectile’s distance to target. I think the way you wrote it still allows for overshooting of the target. For example, if distanceBeforeMoving = 150 units, then the projectile will be moved 200 units this frame, and distanceAfterMoving will be 50 units, but in the wrong direction past our target. However, distanceBeforeMoving will be greater than distanceAfterMoving on that frame in this scenario, and will therefor shoot past our target.
I observed some overshooting sometimes when I implemented your code, then sat down and thought about it, and that’s the conclusion I came up with. Apologies in advance if I am missing something!
I have slightly refactored your code to stop the projectile by checking the remaining distance to target and forgoing the concept of overshooting altogether:
private void Update()
{
Vector3 moveDirection = (targetPosition - transform.position).normalized;
float distanceFromTarget = Vector3.Distance(transform.position, targetPosition);
float moveSpeed = 200f;
if (distanceFromTarget <= moveSpeed)
{
transform.position = targetPosition;
trailRenderer.transform.SetParent(null);
Destroy(this);
Instantiate(bulletHitVFXPrefab, transform.position, Quaternion.identity);
}
else
{
transform.position += moveDirection * moveSpeed * Time.deltaTime;
}
}
Cheers,
-Chris