A
A
Arti-Jack2017-01-06 13:28:06
Java
Arti-Jack, 2017-01-06 13:28:06

How to set the momentum of a bullet once so that at the same time it constantly flies in the right direction?

Good day!
I have a class Box2DBullets , which is a Rectangle of a certain size.
Its initialization:

bdef.type = BodyDef.BodyType.DynamicBody;
        bdef.position.set(x, y);
        b2body = world.createBody(bdef);
        shape.setAsBox(1 / MyGdxGame.PPM, 1 / MyGdxGame.PPM);
        fdef.shape = shape;
        bdef.bullet = true;
        b2body.createFixture(fdef).setUserData("bullet");

And here I need to make sure that when turning to the right, the bullet flies in the same direction (and, accordingly, vice versa, if the turn was made to the left).
To do this, I decided to make a kind of flag. That is, when processing in handlers, I determine in which direction the player turned and then set the ArrayList with bullets the same turn. But so that when the player's direction changes, the bullets that have already flown out also do not change their direction, I decided to make a flag.
if (checkTurning == false) {
       if (factingRight) b2body.applyLinearImpulse(new Vector2(velocity_x, 0), b2body.getWorldCenter(), true);
       if (factingLeft) b2body.applyLinearImpulse(new Vector2(-velocity_x, 0), b2body.getWorldCenter(), true);
       checkTurning = true;
}

But this method doesn't work. As I understand it, the momentum of the bullets must be set constantly.
So isn't there some other way to give the bullet momentum only once, so that it constantly flies in the right direction?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nexeon, 2017-01-06
@Arti-Jack

In the absence of gravity, an object under the action of momentum will have a constant speed that will not change. If there is gravity, then you can set a more powerful momentum so that the bullet flies for a long time.
If this is some kind of rocket, then you can use a physical approach: The rocket has a jet thrust, which sets the rocket in motion. Jet thrust can be simulated with conventional force usingApplyForce()

G
GavriKos, 2017-01-06
@GavriKos

But so that when the player's direction changes, the bullets that have already flown out also do not change their direction, I decided to make a flag.

remember the rotation in the "bullet" class at the time of the shot, and then use this value in setting the momentum, rather than calculating it every time.

That is, you want to assign a value once, so that later it changes itself?
And how should it change itself? You don't want to write methods yourself? Android API? but in fact it's just using the external implementation of the methods. Or do you want the RAM itself to change values? - but this is impossible.
Usually write a separate Update() method to update all values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question