2
\$\begingroup\$

I'm making a 2d platformer in C++, using Box2d for physics and sfml for rendering, I want the player character to move with a constant velocity in the x direction, and to jump when the spacebar is pressed, maintaining it's x velocity. At the moment however, jumping slows the x velocity to a crawl, and falling large distances does the same

b2Vec2 jumpForce(120.0f , -500.0f);
playerBody->ApplyLinearImpulse( jumpForce, playerBody->GetWorldCenter(), true);

is how the impulse is applied when I want to jump, and

b2Vec2 moveSpeed(120,0);
playerBody->SetLinearVelocity(moveSpeed);

is the velocity the body is initialized with, I've turned both linear damping and friction to 0, but with no success.

If anyone has any idea how to solve this issue your help would be greatly appreciated.

edit: These are a couple of solutions I've tried

b2Vec2 jumpForce(playerBody->getLinearVelocity().x, -500.0f);
playerBody->ApplyLinearImpulse( jumpForce, playerBody->GetWorldCenter(), true);

b2Vec2 jumpForce(playerBody->getLinearVelocity().x, -500.0f);
playerBody->SetLinearVelocity( jumpForce, playerBody->GetWorldCenter(), true);
\$\endgroup\$
  • \$\begingroup\$ Box2D damps out velocity each frame. This is a good thing. If you want to keep the velocity nearly constant you'll have to set it each frame. Did you also make the player a kinematic body? \$\endgroup\$ – RandyGaul Nov 4 '14 at 18:30
  • \$\begingroup\$ Player is a dynamic body since I want it to collide with platforms which are static bodies, and I want gravity to act upon it, Velocity isn't been changed every frame, if I print the x velocity every frame I see that it stays at 120 until the player jumps. edit in OP shows other attempts at a solution. \$\endgroup\$ – Eoghan Gibbons Nov 5 '14 at 12:59
2
\$\begingroup\$

Your problem is that you're exceeding Box2D's maximum offset-per-physics-update. This is a common mistake.

There is a maximum movement limit of 2.0 units per time step give in the file b2Settings.h in the source code.

Assuming that you're running at 60 updates per second, your starting velocity of 120 units per second is already exactly at Box2D's maximum movement speed, and adding any more velocity in any direction will result in clamping.

The best solution for this is to change the way that you represent space in Box2D; instead of whatever units you're using at the moment (I assume you're using 'pixels', as that's the most common way people wind up with really high velocities in simulations), use 'meters', or something else which will allow your velocity values to be lower, so you won't reach the maximum movement-per-physics-update limit so quickly.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.