LibGDX Box2D Applying thrust towards direction of bodies angle

What I’m trying to do is take the angle of the ship and apply force to it, so the body moves in the
direction of the mouse as well as the angle/rotation.
I can’t figure the applyForce(force, point, wake) method out. If that is what I’m actually looking for.

So far I have:


public void update(float camPosX, float camPosY){
	//The mouse position
	mouseP.x = (Gdx.input.getX()+playerSprite.getWidth()/2);
	mouseP.y = -((Gdx.input.getY()-ScreenGlobals.HEIGHT));
		
	//If W is pressed apply thrust
	if(Gdx.input.isKeyPressed(Keys.W)){
		body.applyForceToCenter( (mouseP.x-ScreenGlobals.WIDTH/2)*50f, (mouseP.y-ScreenGlobals.HEIGHT/2)*50, true );
     // body.applyForce(force, point, true); //I'm not sure how to do this properly
	}

		
	//Set sprite position to match body position
	float sox = x-playerSprite.getHeight()/2, soy = y-+playerSprite.getWidth()/2;
		
	playerSprite.setPosition(sox, soy);
	playerSprite.setRotation((body.getAngle()-(90*MathUtils.degreesToRadians))*MathUtils.radiansToDegrees);
}

That only moves the body in the direction of the mouse and doesn’t change the angle/rotation of the ship.
What I’m guessing by using applyForce(force, point, wake), is where “force” is the amount of force in which direction,
and point is where the force is applied to at that point on the body. So like a motor on a speed boat.
If this is what I need to achieve this, how is it used to apply force to the bottom of a 32*32 pixel sized
body in the direction of the mouse so the angle/rotation of the ship also faces the mouse?

I’ve tried a bunch of trigonometry stuff but can’t get anything to apply to the physics correctly :confused: I’m pretty new to LibGDX.

What it looks like:

WK4Bl5vIKfw

Thanks

Because apply force to center simply… well applies a force to the center of a body.

You want something like this:


float angle = body.getAngle();
Vector2f target = mousePos - body.getPosition();
float newAngle = Math.atan2(-target.x, target.y );

And apply some sort of linear interpolation if you want to do the turn over time.

I was talking about specifically applyForce(). applyForceToCenter() doesn’t change the angle, it just pushes the body at the mouse.

Not possible, you have to do 1 of 3 things.

Either interpolate between the original angle and the angle of the heading using applyTorque() (or any of the other angular velocity changing thingies).

Or, use setTransform(float x, float y, float angle) right before you move your body.

Or just get hacky and have the sprite change towards the correct angle and don’t bother altering the bodies angle at all. Which is fine for basic primitives (circles, square polygons, rectangles) but obviously not ideal for multi fixture bodies with complex polygons.

I prefer the latter.

Ok thanks very much, I haven’t tested anything yet. Does anyone know how applyForce() is actually used? It baffles me. :stuck_out_tongue: