Skip to content

Instantly share code, notes, and snippets.

@fversnel
Created August 23, 2016 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fversnel/a59f51337ac24c04ab27ecba36a4c224 to your computer and use it in GitHub Desktop.
Save fversnel/a59f51337ac24c04ab27ecba36a4c224 to your computer and use it in GitHub Desktop.
new Thread(() => {
using(CollisionConfiguration collisionConf = new DefaultCollisionConfiguration())
using(Dispatcher dispatcher = new CollisionDispatcher(collisionConf))
using(BroadphaseInterface broadphase = new DbvtBroadphase())
using(DynamicsWorld physicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, null, collisionConf)) {
physicsWorld.Gravity = new Vector3(0, -1, 0);
for (int i = 0; i < _renderableBodies.Length; i++) {
var renderableBody = _renderableBodies[i];
const float mass = 1.0f;
//Add a single cube
var shape = new BoxShape(1f, 1f, 1f);
Vector3 localInertia = Vector3.Zero;
shape.CalculateLocalInertia(mass, out localInertia);
var rbInfo = new RigidBodyConstructionInfo(mass, renderableBody.MotionState, shape, localInertia);
var body = new RigidBody(rbInfo);
rbInfo.Dispose();
var position = renderableBody.InitialPosition.ToBullet();
var rotation = renderableBody.InitialRotation.ToBullet();
Matrix st = Matrix.Translation(position);
st = Matrix.Add(st, Matrix.RotationQuaternion(rotation));
body.WorldTransform = st;
physicsWorld.AddRigidBody(body);
}
isPhysicsEngineStarted.Set();
float fixedTimePassed = 0;
var physicsCancelledToken = _cancelPhysicsToken.Token;
while (!physicsCancelledToken.IsCancellationRequested) {
float currentTime = _stopwatch.ElapsedMilliseconds / 1000f;
float fixedDeltaTime = currentTime - fixedTimePassed;
int totalStepsPerformed = physicsWorld.StepSimulation(fixedDeltaTime, 5, _physicsTimeStep);
fixedTimePassed += _physicsTimeStep * totalStepsPerformed;
if (totalStepsPerformed > 0) {
_motionStateGroup.PrepareRender();
}
//Debug.Log("physics tick at " + (deltaTime));
int sleepIntervalInMs = ((int) (_physicsTimeStep * 1000)) / 4;
Thread.Sleep(sleepIntervalInMs);
}
}
UnityEngine.Debug.Log("Physics engine destroyed");
}).Start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment