Moving rigid bodies with setLinearvelocity

Post Reply
bdsrstnt
Posts: 1
Joined: Tue Mar 25, 2014 8:35 pm

Moving rigid bodies with setLinearvelocity

Post by bdsrstnt »

Hello Everyone!

I made my physics class for my game, using Bullet. It works well, I can make the levels from static rigid bodies, and I can place dynamic rigid bodies.
They collide, it works fine.

The problem is, when I try to move the player, I use the setLinearVelocity method. The velocity comes from the user input (WASD).

I start the game, the player moves if I start pressing one of the movement keys in the beginning. When I release a button, the velocity on the axis is set to 0 (NULL), so the body won't move with the keys released (W-S for Z, A-D for X axis).

So after I release the keys, the body stops. When I try to move again, pressing the keys, the body won't move. It stays where it stopped after the first keyrelease.

If I press the movement keys in the beginning, and I don't release it, or I just change the direction, the body will move properly.
Releasing all the keys, the body stops and won't move, even if I press the keys.

Here's the code, which involves the setLinearVelocity:

Code: Select all

//the rigid body of the player is stored in getCollisionObjectArray()[0]
//TODO: I should store a pointer to the rigid body of the player int the Player class
        btCollisionObject* obj = btPhysics->getDynamicsWorld()->getCollisionObjectArray()[0];
	btRigidBody* body = btRigidBody::upcast(obj);
	btVector3 v = body->getLinearVelocity();

	v.setX(player->getVelocity().x);
	v.setZ(player->getVelocity().z);
	body->setLinearVelocity(v);

	btPhysics->step();

	if (body && body->getMotionState())
	{
		btTransform trans;
		body->getMotionState()->getWorldTransform(trans);

		player->setPositon(Vector3Df(
			trans.getOrigin().getX(),
			trans.getOrigin().getY(),
			trans.getOrigin().getZ()
			));
	}
Input handling:

Code: Select all

Vector3Df v = controlledGame->getPlayer()->getVelocity();
//X 
	if(GetKeyState('D') & 8000)
		v.x = PLAYER_X_VEL;
	else if(GetKeyState('A') & 8000)
		v.x = -PLAYER_X_VEL;
	else
		v.x = 0.0f;

//Z
	if(GetKeyState('W') & 8000)
		v.z = -PLAYER_X_VEL;
	else if(GetKeyState('S') & 8000)
		v.z = PLAYER_X_VEL;
	else
		v.z = 0.0f;
controlledGame->getPlayer()->setVelocity(v);
Thanks for reading, answering, pointing things out.

Have a nice day!
Flix
Posts: 456
Joined: Tue Dec 25, 2007 1:06 pm

Re: Moving rigid bodies with setLinearvelocity

Post by Flix »

You might need to call body->activate() before setting the linear velocity, or you can just forget about it, by setting the DISABLE_DEACTIVATION state.
Post Reply