1
votes

I am creating a Java desktop 2D Game using LibGDX.

I need to be able to move objects (controlled by the player with W/A/S/D).
The movement speed is always the same (read out from a field of the moving object).

While they are moving, they should still be affected by physics.
This means that when moving away from a magnet would make you move slower, moving towards it makes you faster and moving past it would cause you to move a curve. (see blue part of image)

Also a single impulse in while moving would knock you away but you keep moving (see red part of image)

You should also be able to change direction or stop, only stopping your own movement, so you will still be affected by physics.


So I need to apply constant forces that will still be accessible (and removable) after the next step.
Can I do this with Box2D?
-If yes, how?
-If no, any other libraries that can do this? I don't really need density and stuff like that, the use cases in the image is pretty much all I need (+ Collision Detection).

image for visualization

*A magnet would be a body constantly pulling other bodies in a certain range to itself
*Kockback would just be a simple impulse or the collision of a projectile with the object.



EDIT: If you know The Binding of Isaac, thats the kinda physics I'm aiming for.

1
I would call applyForceToCenter() on the entity every iteration, based on the distance and direction of the magnet.Steve Smith

1 Answers

2
votes

Set the distance where the magnet has his influence:

float magnetRadius = 30;

Set the attractive force of the magnet:

float magnetForce = 400;

Get the position of the player and of the magnet:

Vector2 magnetPos = magnet.getWorldCenter();
Vector2 playerPos = player.getWorldCenter();

Now calculate the distance between the player and the magnet:

Vector2 magnetDist = new Vector2((playerPos.x - magnetPos.x), (playerPos.y - magnetPos.y));
float distance = (float) Math.sqrt((magnetPos.x) * (magnetPos.x) + (magnetPos.y) * (magnetPos.y));

Then, if the player is inside the magnet's radius, you must apply a force to him that depends on the distance of the player from the magnet:

if (distance <= magnetRadius) {
   float vecSum = Math.abs(magnetDist.x)+Math.abs(magnetDist.y);
   Vector2 force = new Vector2((magnetForce*magnetDist.x * ((1/vecSum)*magnetRadius/distance)), (magnetForce*magnetDist.y * ((1/vecSum)*planetRadius/distance)));
   player.applyForceToCenter(force, true);
}