- Home /
How to make the distance to target adjust itself
Hello! I have made a script that impulses the player towards the click. When the distance is small enough (say, lesser than 10), the force stops being added.
if(travelToTarget == true)
{
//target is the position of the mouse click
float distanceToTarget = Vector3.Distance(player.transform.position, target);
float distanceToTargetLess = distanceToTarget * 0.9f;
// as it turns to less, the less makes it even less
if(distanceToTargetLess < distanceToTarget)
{
Debug.Log("Distance: " + distanceToTarget);
target.z = 0;
Vector2 direction = (target - player.transform.position).normalized;
rb.AddForce(direction * speed, ForceMode2D.Impulse);
}
else
{
travelToTarget = false;
}
}
}
The problem is, if you click within 10 units from the player, he doesn't move. So you would have to set the small-enough distance to change depending on the distance to target, which I made * 0.9 (if the distance was 10, then it would have to be 9 for it to stop).
But, stay with me here, if the distance goes from 10 to 9, now it has to go from 9 to 8.1, and so on.
So what am I getting wrong here?? How do I make the small-enough distance to adjust with the distanceToTarget and not make it decrease infinitely?
Answer by ray2yar · Jan 29, 2019 at 01:40 AM
Why stop applying force at 10? Why not apply it but a portional magnitudes less until it reaches the target? To avoid over shooting you could add logic for stopping.
Your answer
