How do I prevent other dynamic bodies from affecting the player's velocity with Box2D?

Posted by Milo on Game Development See other posts from Game Development or by Milo
Published on 2014-01-04T02:00:38Z Indexed on 2014/06/03 21:42 UTC
Read the original article Hit count: 324

Filed under:
|
|

I'm working on my player object for my game.

PhysicsBodyDef def;
def.fixedRotation = true;
def.density = 1.0f;
def.position = Vec2(200.0f, 200.0f); 
def.isDynamic = true;
def.size = Vec2(50.0f,200.0f);

m_player.init(def,&m_physicsEngine.getWorld());

This is how he moves:

b2Vec2 vel = getBody()->GetLinearVelocity();
float desiredVel = 0;

if (m_keys[ALLEGRO_KEY_A] || m_keys[ALLEGRO_KEY_LEFT])
{
    desiredVel = -5;
}
else if (m_keys[ALLEGRO_KEY_D] || m_keys[ALLEGRO_KEY_RIGHT])
{
    desiredVel = 5;
}
else
{
    desiredVel = 0;
}

float velChange = desiredVel - vel.x;
float impulse = getBody()->GetMass() * velChange; //disregard time factor
getBody()->ApplyLinearImpulse( b2Vec2(impulse,0), getBody()->GetWorldCenter(),true);

This creates a few problems. First, to move the player at a constant speed he must be given a high velocity. The problem with this is if he just comes in contact with a small box, he makes it move a lot.

Now, I can fix this by lowering his density, but then comes my main issue: I need other objects to be able to run into him, but when they do, he should be like a static wall and not move.

I'm not sure how to do that without high density. I cannot use collision groups since I still need him to be solid toward other dynamic things.

How can this be done? Essentially, how do I prevent other dynamic bodies from affecting the player's velocity?

© Game Development or respective owner

Related posts about c++

Related posts about physics