Here is the link below, how I move bullet to target position using touch point. (Move a body to the touched position using libgdx and box2d)
My problem is how do I stop the bullet body, if bullet body has reach target position.
I already tried the below code, and its working properly.
PIXEL_TO_METER = 1/32.0f
time step = 1/45.0f, velocity iteration = 6, position iteration = 2
float distanceTravelled = targetDirection.dst(bulletPosition);
if(distanceTravelled >= MAX_DISTANCE){
// stop
} else {
// move body
}
but I want to stop the bullet on target position, nor on MAX_DISTANCE. But I have no idea how to do it.
You need to check whether the bullet is near your target enough to say that it has reach target.
float distance = targetPosition.dst(bulletPosition);
if(distance <= DEFINED_PRECISION){
// stop
// also you can set the target's position to the bullet here
} else {
// move body
}
Why near not exactly at the point? The bullet is going with some defined speed let say 10px per second. If you have 60fps
that means that in every frame the bullet is being moved by 10/60px.
If the bullet is starting with position 0
it's next position (in next frames) will be
1/6 (frame 1)
2/6 (frame 2)
3/6 (frame 3)
...
If target is at the position 1.5/6
you can see that although in frame 1
bullet hasn't reached the target yet in the next fram it has passed it and it's like collision was never detected. That's why you need to define some precision. It's value should be at least of 1 frame step so in this case it would be 1/6
float DEFINED_PRECISION = 1/6f;