How to make the bullet stop accurately when destination is reached?

In the below code, is the method I use to move a bullet to its destination and stop when bullet is near to destination. But the problem is the bullet is stopping not accurately, sometimes there's a small offset or span or sometimes is accurate depends on the angle.

public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) {     Vector2 targetDirection = targetPosition.cpy().sub(currentPosition);     return targetDirection             .nor(); }  final float SPEED = 6; float pos = bulletPosition.len(); float des = bullet.destination.len(); float tol = Constants.TIME_STEP * SPEED;  if(MathUtils.isEqual(pos,des, tol)) {     body.setLinearVelocity(0,0);  } else {     body.setLinearVelocity(getVelocity(bulletPosition, destination).scl(SPEED)); } 


if(MathUtils.isEqual(pos, des, tol)) {      // quick & dirty way      body.setTransform(destination, angle);      // better way      ... } 


Quick & Dirty Way:
You can simply teleport the bullet to location you want after it stops.

Long & Better Way:
For the last moments of movement, you can disable the physics and control the movement yourself by lerp'ing (or any other way, lerp is my favorite) towards the target. This way, you can stop the bullet whenever you want.

I would solve the situation like this in Unity, and actually this might be a better way than the two above:

float minDisableDistance, minStopDistance, bulletSpeed;
Transform target;

// I'm skipping the parts that you create the bullet, and simply do the job on these:
GameObject bullet; //Assuming this is the bullet.
Rigidbody bulletRigidbody; //Assuming this is the rigidbody of bullet.

void Update()
    Vector3 relPos = target.position - bullet.postion;
    float distance = relPos.magnitude;

    if(distance > minDisableDistance)
        //use physics.
        bulletRigidbody.velocity = 0;

        if(distance > minStopDistance)
            bullet.position += bulletSpeed * relPos.normalized * time.deltaTime;
            bullet.position = target.position;

I found out the best way! I just use the Vector2 dst method to get the distance between the destination. And hooray!! it was accurate!

float distance = bulletPosition.cpy().dst(destination);

float tol = (Constants.TIME_STEP * SPEED) / 2;

if(distance <= tol) {

     body.setLinearVelocity(0, 0);


Category: libgdx Time: 2016-07-30 Views: 0
Tags: box2d libgdx

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.131 (s). 12 q(s)