Search code examples
javalibgdxbox2d

Libgdx Box2d Body move in a linear direction?


I made a body which I want to move when a button is clicked, I have been able to move the body using body.setLinearVelocity() but it's not accurate. Let's say I want to move my body for seven meters with a linear X velocity of 40, how do I do that?

//BODY MOVEMENT
//timer = I try to move the body for a certain amount of time
/*isMoveRight and isMoveLeft are Just booleans for activating and deactivating movement*/
        if(Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)){
            timer = 0f;
            isMoveRight = true;
            isMoveLeft = false;
        }else if(Gdx.input.isKeyJustPressed(Input.Keys.LEFT)){
            timer = 0f;
            isMoveLeft = true;
            isMoveRight = false;
        }

        if(isMoveRight == true && timer < 0.1f){
            timer += 1f * delta;   //activate timer
            body.setLinearVelocity(52f, 0f);
        }else if(isMoveLeft == true && timer < 0.1f){
            timer += 1 * delta;
            body.setLinearVelocity(-52f, 0f);
        }

I could just use body.setTransform() but I need the body to actually move and not to teleport. Thank you in advance


Solution

  • I don't know how complete your code sample is but from waht I see here, you are at least missing the part where you reset the velocity to 0 after 0.1 seconds.

    else {
        body.setLinearVelocity(0F, 0F);
    }
    

    Apart from that your method has a slight vagueness in the moved distance because dependent on your frame rate your check timer < 0.1f is not very exact:

    timer = 0.099 -> distance = 5.148
    timer = 0.132 -> distance = 6.881 (one frame later with 30 frames/second)
    

    Some (untested) ideas how to handle this problem:

    1. Use a RopeJoint to enforce a maximum distance between the body and the starting point (which has to be a body as well in this case)
    2. Measure the distance (use the Vector2 class) and teleport it back to the point at max distance if needed. (You should use the distance instead of the timer anyway)
    3. Slow your body down if it gets close to the target, this will at least help to reduce the error