# Physics for movement in a topdown 2d game?

I'm implementing player movement for a simple topdown game, how would I handle more "advanced" concepts in physics to make my player movement feel more natural? Right now I have something like this:

void update(double delta) {
dx = dy = 0;

if (left) {
dx -= 1;
}
if (right) {
dx += 1;
}
if (up) {
dy -= 1;
}
if (down) {
dy += 1;
}

if (dx != 0 || dy != 0) {
x += dx * delta;
y += dy * delta;
}
}


How would I go about implementing things like friction, acceleration, drag, and so on?

• Language? Based on what you showed as this could be either c++, java and C# (and many more) Oct 17, 2016 at 5:54

I recommend you to check on box2d physics library and steering-behavior concept and also iforce2d will give you a better examples. These will help you to bring characters to life. I assume that you are using java.

This is how you create the world. This will provide you automatically the physics you want, force, impulse, gravity, velocity, acceleration, angle, torque etc.

// earth gravity
Vector2 gravity = new Gravity(0, -9.8f);
World world = new World(gravity, true);


This is how to update the world. Read more if you have questions

world.step(POSITION_ITERATION, VELOCITY_ITERATION);


This is how you create the body.

BodyDef bodDef = new BodyDef();

bodDef.position.set(x, y);
bodDef.type = BodyType.DynamicBody;

Body body = world.createBody(bodDef);

FixtureDef fixDef = new FixtureDef();

fixDef.filter.categoryBits = categoryBits;
fixDef.density = density;
fixDef.friction = friction;
fixDef.restitution = restitution;
fixDef.isSensor = isSensor;
fixDef.shape = shape;

body.createFixture(fixDef);

// also don't forget to dispose shape
shape.dispose();


This is how you use the body.

body.applyForce(...)
body.setLinearVelocity(...)
body.setTransform(...)
// and so on...