Code: Select all
// Enter these commands, followed by <Return>, to control the player:
// "l" - Left
// "r" - Right
// "u" - Up
#include <btBulletDynamicsCommon.h>
#include <stdio.h>
#include <time.h>
#include <boost/timer/timer.hpp>
#include <boost/thread.hpp>
boost::mutex playerBodyLock;
void reader(btRigidBody *body);
int main() {
btDefaultCollisionConfiguration config;
btCollisionDispatcher dispatcher(&config);
btDbvtBroadphase broadphase;
btSequentialImpulseConstraintSolver solver;
btDiscreteDynamicsWorld world(&dispatcher, &broadphase, &solver, &config);
world.setGravity(btVector3(0, -10, 0));
btStaticPlaneShape environmentShape(btVector3(0.0f, 1.0f, 0.0f), -3);
btDefaultMotionState environmentMotionState;
btCapsuleShape playerShape(1.0f, 2.0f);
btDefaultMotionState playerMotionState;
btVector3 playerInertia;
playerShape.calculateLocalInertia(30, playerInertia);
btRigidBody::btRigidBodyConstructionInfo environmentBodyCI(0.0f, &environmentMotionState, &environmentShape);
btRigidBody environmentBody(environmentBodyCI);
btRigidBody::btRigidBodyConstructionInfo playerBodyCI(30.0f, &playerMotionState, &playerShape, playerInertia);
btRigidBody playerBody(playerBodyCI);
playerBody.setAngularFactor(btVector3(0.0f, 0.0f, 0.0f));
playerBody.setLinearFactor(btVector3(1.0f, 1.0f, 0.0f));
world.addRigidBody(&environmentBody);
world.addRigidBody(&playerBody);
boost::thread readThread(reader, &playerBody);
boost::timer::cpu_timer timer;
timer.start();
float lastUpdate = timer.elapsed().wall / 1e9;
btTransform playerTransform;
while(true) {
{
boost::lock_guard<boost::mutex> lock(playerBodyLock);
float now = timer.elapsed().wall / 1e9;
world.stepSimulation(now - lastUpdate, 5);
playerBody.getMotionState()->getWorldTransform(playerTransform);
printf("%f\t%f\t%f\n", playerTransform.getOrigin().x(), playerTransform.getOrigin().y(), playerTransform.getOrigin().z());
lastUpdate = now;
}
boost::this_thread::sleep(boost::posix_time::millisec(40));
}
}
void reader(btRigidBody *body)
{
while(true) {
char command[5];
fgets(command, sizeof(command), stdin);
switch(command[0]) {
case 'l': {
boost::lock_guard<boost::mutex> lock(playerBodyLock);
body->applyCentralImpulse(btVector3(-30, 0, 0));
break;
}
case 'r': {
boost::lock_guard<boost::mutex> lock(playerBodyLock);
body->applyCentralImpulse(btVector3(30, 0, 0));
break;
}
case 'u': {
boost::lock_guard<boost::mutex> lock(playerBodyLock);
body->applyCentralImpulse(btVector3(0, 100, 0));
break;
}
}
}
}
My operating system is Windows 7 x64. I use Bullet 2.80-rev2531 in the "Release" configuration, compiled with Visual Studio 2010. My processor is an Intel Core i7 Q820 @ 1.73 GHz. As for the JS version, I've tested it with the latest Chrome (on the stable update channel) and Firefox 12 (Beta) on the same system.
- Raphael