简体   繁体   中英

libgdx apply force in direction rectangle is facing

I'm just starting out with box2d an I'm trying to make a rocket(rectangle for now) fly, it just stands vertically when the game starts and I want to apply force from the bottom part of the rectangle, because that's where the engine would be, and also in the direction the rectangle is facing. I tried doing this

    body.applyLinearImpulse(getUserData().getBoosterLinearImpulse(), new Vector2(body.getWorldCenter().x, body.getWorldCenter().y - Constants.ROCKET_HEIGHT), true);

This is a method that gets executed when the bottom right of the screen is pressed. It only works when the rectangle is standing still. I obviously don't really know what I'm doing. I also have another question: what's the difference between applyLineairForce and applyForce, and how do I best learn to work with box2d as I don't find it easy (which is not a problem)?

If I'm understanding this right you want to know the difference between a applyLinearImpulse and a applyForce. An impulse is a one-off application of force which would generally be used for jumps in a game whereas a force would be something applied every frame say to increase the speed of a car.

In order for you to apply force to your rocket, you could use something like this:

       // gets x force based on angle
        float x = (float)Math.sin(body.getAngle() - Math.PI); // minus PI as objects start off facing right
        // gets y force based on angle
        float y = (float)Math.cos(body.getAngle());

        //apply force to center (applies force to middle so no rotation )
        //body.applyForceToCenter( new Vector2(
        //      body.getMass()* (x * 12),
        //      body.getMass()*(y*12)), true);

        //NOTE: bodies must be set to .fixedRotation = false in order to rotate;

        //apply force to a point on body (will create rotational force ) 
        body.applyForce( new Vector2(
                body.getMass()* (x * 12),//x force to apply
                body.getMass()* (y * 12)), //y force to apply
                // apply force to body at 0.5f(halfway for 1f wide object) x and -5 y
                body.getWorldPoint(new Vector2(0.5f,-5)),true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM