bullet を使う2

前回の続き。
初期化したワールド空間に地面と球体を追加し、重力に応じて落っこちていく物体の座標を計算する。

// 地面の初期化
btCollisionShape* ground = new btStaticPlaneShape(btVector3(0.0, 1.0, 0.0), 1);
btCollisionShape* fall = new btSphereShape(1);

btDefaultMotionState* groundMotion =
	new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
btRigidBody::btRigidBodyConstructionInfo groundConstInfo(0, groundMotion, ground, btVector3(0, 0, 0));
btRigidBody* groundRigidBody = new btRigidBody(groundConstInfo);

// ワールド空間に地面を追加
m_world->addRigidBody(groundRigidBody);

// 球体の初期化
btDefaultMotionState* fallMotion =
	new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 100, 0)));
btScalar mass = 1;
btVector3 fallInertia(0, 0, 0);
fall->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallConstInfo(mass, fallMotion, fall, fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallConstInfo);

// ワールド空間に球体を追加
m_world->addRigidBody(fallRigidBody);

// 座標計算
for (int i = 0 ; i < 400 ; i++)
{
	m_world->stepSimulation(1.0 / 60.0, 10);

	btTransform tran;
	fallRigidBody->getMotionState()->getWorldTransform(tran);

	printf("x = %f, y = %f, z = %f\n", tran.getOrigin().getX(), tran.getOrigin().getY(), tran.getOrigin().getZ());
}

// 後処理
m_world->removeRigidBody(groundRigidBody);
m_world->removeRigidBody(fallRigidBody);

delete groundRigidBody;
delete groundMotion;

delete fallRigidBody;
delete fallMotion;

delete ground;
delete fall;



これもほぼチュートリアルからのコピペだが、基本的にはワールド空間にオブジェクトを追加して、stepSimulation() で座標計算をしていくことになる。
ここでは、1/60秒後の座標を計算している。
また衝突した際にコールバックを呼んだりできるようなので、そのあたりを後で調べる。


コンパイル例】
g++ -o bullet_jikken main.cc -lbulletcollision -lbulletdynamics -lbulletmath -lbulletsoftbody