An alternative to reach the destination

[Unit Move | GameDev.tv](Unit Move - CodeMonkey)
Here’s an alternative that doesn’t need the ‘magic number’ at all and always stops at the target position.

Vector3 toTarget = targetPosition - transform.position;
float dist = toTarget.magnitude;
if (dist > 0)
{
	Vector3 move = toTarget.normalized * moveSpeed * Time.deltaTime;
	// if we're going to overshoot the target
	if (move.magnitude > dist)
	{
		// move exactly to target location
		move = toTarget;
	}
	transform.position += move;
}
10 Likes

Yup that’s a great alternative, good job!
I actually do pretty much exactly that in the Bullet Projectile script, since the bullet moves really quickly it requires testing if it overshoots the target instead of just min distance.

Nice. I particularly like the fact that the end position is set, so you can be sure that the unit ends up on the exact target position. In this case, it might not be critically important, but this is a good solution. ( I got stuck constantly setting the position and wondering if I should check for an actual match, but comparing floats is a pain :grinning: )

1 Like

Not quite exactly that. Unfortunately the code presented in 4_EN_UTS only works for half of the cases, where the bullet starts closer than half a frame’s distance from the target. Otherwise it overshoots for one frame anyway. The code provided by the OP can be used almost word-for-word in the Bullet Projectile script and it solves that problem also.

EDIT: later in the video @codemonkey picks up on this and sets the bullet position to the target position in the case where before distance is less than after, but I’m still not sure this catches the situation where the bullet is in the first half of the frame distance and still overshoots by less than half the frame distance. I may be wrong about this, need to think about it some more…

For the bullet, this way of handling makes sense. But after testing it for the movement, I would say its not the right solution. When setting the position right on target, the target rotation changes and the unit rotates a bit on arrival (Towards 0,0,0; thats why it went unnoticed maybe, units are rotated this way by default). So there is an additional check needed. So for movement I would say, the simpler solution by codemonkey is better, problems would occur only under 20fps, nobody would play the game with under 20fps anyways.

Could be wrong though, I played alot with the code, maybe I just introduced new bugs and I’m talking nonsense here :stuck_out_tongue:

Privacy & Terms