public static RigidBody CreateRigidBodyFromTgcMesh(TgcMesh mesh, TGCVector3 position, float mass, float friction) { var meshAxisRadius = mesh.BoundingBox.calculateAxisRadius().ToBsVector; var boxShape = new BoxShape(meshAxisRadius); var transformationMatrix = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix; transformationMatrix.Origin = position.ToBsVector; DefaultMotionState motionState = new DefaultMotionState(transformationMatrix); var boxLocalInertia = boxShape.CalculateLocalInertia(mass); var bodyInfo = new RigidBodyConstructionInfo(mass, motionState, boxShape, boxLocalInertia); var rigidBody = new RigidBody(bodyInfo) { LinearFactor = TGCVector3.One.ToBsVector, Friction = friction, RollingFriction = 1f, AngularFactor = new Vector3(1f, 0.2f, 1f), SpinningFriction = 0.7f }; return(rigidBody); }
public Physics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf); World.Gravity = new Vector3(0, -10, 0); // create the ground CollisionShape groundShape = new BoxShape(50, 1, 50); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; CollisionShape colShape = new BoxShape(1); CollisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); float start_x = StartPosX - ArraySizeX / 2; float start_y = StartPosY; float start_z = StartPosZ - ArraySizeZ / 2; int k, i, j; for (k = 0; k < ArraySizeY; k++) { for (i = 0; i < ArraySizeX; i++) { for (j = 0; j < ArraySizeZ; j++) { Matrix startTransform = Matrix.Translation( 2 * i + start_x, 2 * k + start_y, 2 * j + start_z ); // using motionstate is recommended, it provides interpolation capabilities // and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); RigidBody body = new RigidBody(rbInfo); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } }
public void Init(TgcSimpleTerrain terrain) { collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); broadphaseInterface = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphaseInterface, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = gravity; var ballShape = new SphereShape(50); var ballTransform = TGCMatrix.Identity; ballTransform.Origin = initialPosition; var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix); var ballInertia = ballShape.CalculateLocalInertia(1f); var ballInfo = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballInertia); RigidCamera = new RigidBody(ballInfo); RigidCamera.SetDamping(0.9f, 0.9f); //esto es para que no le afecte la gravedad al inicio de la partida //RigidCamera.ActivationState = ActivationState.IslandSleeping; dynamicsWorld.AddRigidBody(RigidCamera); var heighmapRigid = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terrain.getData()); dynamicsWorld.AddRigidBody(heighmapRigid); }
protected RigidBody ResetRigidBody(RigidBody rb, float newMass, BulletSharp.Math.Vector3 newInertia, Matrix startTransform, CollisionShape shape, float friction = 0.5f, bool isKinematic = false) { // basically detroys a rigid body and re-initializes it efficiently // doesn't recalculate moment of inertia or re-create the gfx object //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects\ float mass = newMass; BulletSharp.Math.Vector3 localInertia = newInertia; DestroyRigidBody(rb); DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); rbInfo.Friction = friction; RigidBody body = new RigidBody(rbInfo); if (isKinematic) { body.CollisionFlags = body.CollisionFlags | BulletSharp.CollisionFlags.KinematicObject; body.ActivationState = ActivationState.DisableDeactivation; } rbInfo.Dispose(); m_world.AddRigidBody(body); return(body); }
public FisicaMundo() { //Implementación Iniciales collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -10f, 0).ToBulletVector3() }; var cuerpoPiso = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0) { LocalScaling = new TGCVector3().ToBulletVector3() }; MotionState movimientoPiso = new DefaultMotionState(); piso = new RigidBody(new RigidBodyConstructionInfo(0, movimientoPiso, cuerpoPiso)) { RollingFriction = 0.3f, Restitution = 0.4f, UserObject = "floorBody" }; dynamicsWorld.AddRigidBody(piso); }
public RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape) { //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.0f); Vector3 localInertia = Vector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBody body; using (var rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia)) { body = new RigidBody(rbInfo); } ownerWorld.AddRigidBody(body); return(body); }
private RigidBody CreateRigidBody(float mass, Matrix4 startTransform, CollisionShape shape) { bool isDynamic = (mass != 0.0f); Vector3 localInertia = Vector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); RigidBody body = new RigidBody(rbInfo); body.SetSleepingThresholds(0, 0); body.ContactProcessingThreshold = 0; body.CcdMotionThreshold = 0; //World.AddRigidBody(body); return(body); }
public void Init() { #region MUNDO //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -20f, 0).ToBsVector }; #endregion #region PISO var d3dDevice = D3DDevice.Instance.Device; //El piso es un plano estatico se dice que si tiene masa 0 es estatico. var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBsVector, 0); var floorMotionState = new DefaultMotionState();// Matrix.Translation(0f, 200f, -700f));//esto puede ir sin parametro y funciona var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); dynamicsWorld.AddRigidBody(floorBody); //Cargamos objetos de render del framework. //var floorTexture = TgcTexture.createTexture(d3dDevice, GameModel.mediaDir + "texturas\\terrain\\TerrainTexture1.jpg"); //floorMesh = new TgcPlane(new TGCVector3(0, 0, 0), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture); #endregion }
// Cutting public RigidBody LocalCreateRigidBody(float mass, BulletSharp.Math.Vector3 startpos, CollisionShape shape, bool isKinematic = false) { //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.0f); BulletSharp.Math.Vector3 localInertia = BulletSharp.Math.Vector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects BulletSharp.Math.Matrix matrixtrans = BulletSharp.Math.Matrix.Identity; matrixtrans.Origin = startpos; DefaultMotionState myMotionState = new DefaultMotionState(matrixtrans); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); RigidBody body = new RigidBody(rbInfo); if (isKinematic) { body.CollisionFlags = body.CollisionFlags | BulletSharp.CollisionFlags.KinematicObject; body.ActivationState = ActivationState.DisableDeactivation; } rbInfo.Dispose(); return(body); }
/// <summary> /// Crea una coleccion de triangulos para Bullet a partir de los triangulos generados por un heighmap /// o una coleccion de triangulos a partir de un Custom Vertex Buffer con vertices del tipo Position Texured. /// Se utilizo el codigo de un snippet de Bullet http://www.bulletphysics.org/mediawiki-1.5.8/index.php?title=Code_Snippets /// </summary> /// <param name="triangleDataVB">Custom Vertex Buffer que puede ser de un Heightmap</param> /// <returns>Rigid Body del terreno</returns> public static RigidBody CreateSurfaceFromHeighMap(CustomVertex.PositionTextured[] triangleDataVB) { //Triangulos var triangleMesh = new TriangleMesh(); int i = 0; TGCVector3 vector0; TGCVector3 vector1; TGCVector3 vector2; while (i < triangleDataVB.Length) { var triangle = new Triangle(); vector0 = new TGCVector3(triangleDataVB[i].X, triangleDataVB[i].Y, triangleDataVB[i].Z); vector1 = new TGCVector3(triangleDataVB[i + 1].X, triangleDataVB[i + 1].Y, triangleDataVB[i + 1].Z); vector2 = new TGCVector3(triangleDataVB[i + 2].X, triangleDataVB[i + 2].Y, triangleDataVB[i + 2].Z); i = i + 3; triangleMesh.AddTriangle(vector0.ToBsVector, vector1.ToBsVector, vector2.ToBsVector, false); } CollisionShape meshCollisionShape = new BvhTriangleMeshShape(triangleMesh, true); var meshMotionState = new DefaultMotionState(); var meshRigidBodyInfo = new RigidBodyConstructionInfo(0, meshMotionState, meshCollisionShape); RigidBody meshRigidBody = new RigidBody(meshRigidBodyInfo); return(meshRigidBody); }
/// <summary> /// Se crea una capsula a partir de un radio, altura, posicion, masa y si se dedea o no calcular /// la inercia. Esto es importante ya que sin inercia no se generan rotaciones que no se /// controlen en forma particular. /// </summary> /// <param name="radius">Radio de la Capsula</param> /// <param name="height">Altura de la Capsula</param> /// <param name="position">Posicion de la Capsula</param> /// <param name="mass">Masa de la Capsula</param> /// <param name="needInertia">Booleano para el momento de inercia de la Capsula</param> /// <returns>Rigid Body de una Capsula</returns> public static RigidBody CreateCapsule(float radius, float height, TGCVector3 position, float mass, bool needInertia) { //Creamos el shape de la Capsula a partir de un radio y una altura. var capsuleShape = new CapsuleShape(radius, height); //Armamos las transformaciones que luego formaran parte del cuerpo rigido de la capsula. var capsuleTransform = TGCMatrix.Identity; capsuleTransform.Origin = position; var capsuleMotionState = new DefaultMotionState(capsuleTransform.ToBsMatrix); RigidBodyConstructionInfo capsuleRigidBodyInfo; //Calculamos o no el momento de inercia dependiendo de que comportamiento //queremos que tenga la capsula. if (!needInertia) { capsuleRigidBodyInfo = new RigidBodyConstructionInfo(mass, capsuleMotionState, capsuleShape); } else { var capsuleInertia = capsuleShape.CalculateLocalInertia(mass); capsuleRigidBodyInfo = new RigidBodyConstructionInfo(mass, capsuleMotionState, capsuleShape, capsuleInertia); } var localCapsuleRigidBody = new RigidBody(capsuleRigidBodyInfo); localCapsuleRigidBody.LinearFactor = TGCVector3.One.ToBsVector; //Dado que hay muchos parametros a configurar el RigidBody lo ideal es que //cada caso se configure segun lo que se necesite. return(localCapsuleRigidBody); }
//---------------------------------------------------------------------------------------------- public RigidBody LocalCreateRigidBodyMultiWorld(float mass, ref IndexedMatrix startTransform, CollisionShape shape, DiscreteDynamicsWorld world) { Debug.Assert((shape == null || shape.GetShapeType() != BroadphaseNativeTypes.INVALID_SHAPE_PROXYTYPE)); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = !MathUtil.CompareFloat(mass, 0f); IndexedVector3 localInertia = IndexedVector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects //#define USE_MOTIONSTATE 1 //#ifdef USE_MOTIONSTATE DefaultMotionState myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity); RigidBodyConstructionInfo cInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); RigidBody body = new RigidBody(cInfo); if (BulletGlobals.g_streamWriter != null && true) { BulletGlobals.g_streamWriter.WriteLine("localCreateRigidBody [{0}] startTransform", body.m_debugBodyId); MathUtil.PrintMatrix(BulletGlobals.g_streamWriter, startTransform); BulletGlobals.g_streamWriter.WriteLine(""); } world.AddRigidBody(body); return(body); }
public RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape) { collisionShapes.Add(shape); bool isDynamic = (mass != 0.0f); Vector3 localInertia = Vector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBody body; using (var rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia)) { body = new RigidBody(rbInfo); } World.AddRigidBody(body); return(body); }
public virtual RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape, bool isKinematic = false) { //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.0f); Vector3 localInertia = Vector3.Zero; if (isDynamic) { shape.CalculateLocalInertia(mass, out localInertia); } //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia); RigidBody body = new RigidBody(rbInfo); if (isKinematic) { body.CollisionFlags = body.CollisionFlags | CollisionFlags.KinematicObject; body.ActivationState = ActivationState.DisableDeactivation; } rbInfo.Dispose(); _world.AddRigidBody(body); return(body); }
/// <summary> /// Se crea uncuerpo rigido a partir de un TgcMesh, pero no tiene masa por lo que va a ser estatico. /// </summary> /// <param name="mesh">TgcMesh</param> /// <returns>Cuerpo rigido de un Mesh</returns> public RigidBody CreateRigidBodyFromTgcMesh(TgcMesh mesh) { var vertexCoords = mesh.getVertexPositions(); TriangleMesh triangleMesh = new TriangleMesh(); for (int i = 0; i < vertexCoords.Length; i = i + 3) { triangleMesh.AddTriangle(vertexCoords[i].ToBulletVector3(), vertexCoords[i + 1].ToBulletVector3(), vertexCoords[i + 2].ToBulletVector3()); } var transformationMatrix = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix; DefaultMotionState motionState = new DefaultMotionState(transformationMatrix); var bulletShape = new BvhTriangleMeshShape(triangleMesh, false); var boxLocalInertia = bulletShape.CalculateLocalInertia(0); var bodyInfo = new RigidBodyConstructionInfo(0, motionState, bulletShape, boxLocalInertia); var rigidBody = new RigidBody(bodyInfo); rigidBody.Friction = 0.4f; rigidBody.RollingFriction = 1; rigidBody.Restitution = 1f; return(rigidBody); }
public BulletXNAObject(Game game, string modelAssetName, float mass, DefaultMotionState motionState, CollisionShape collisionShape, Vector3 localInertia, bool ghost) : base(game, modelAssetName) { m_motionState = motionState; IsGhost = ghost; SetUpBulletPhysicsBody(mass, motionState, collisionShape, localInertia); }
/// <summary> /// Se crea una capsula a partir de un radio, una altura y una posicion. /// Los valores de la masa y el calculo de inercia asociado estan fijos para que no haya comportamiento erratico. /// </summary> /// <param name="radius"></param> /// <param name="height"></param> /// <param name="position"></param> /// <returns></returns> public static RigidBody CreateCapsule(float radius, float height, TGCVector3 position) { //Creamos el shape de la Capsula a partir de un radio y una altura. var caspsuleShape = new CapsuleShape(radius, height); //Armamos las transformaciones que luego formaran parte del cuerpo rigido de la capsula. var capsuleTransform = TGCMatrix.Identity; capsuleTransform.Origin = position; var capsuleMotionState = new DefaultMotionState(Matrix.Translation(position.ToBsVector)); // Utilizamos una masa muy grande (1000 Kg) para calcular el momento de inercia de forma que la capsula no // genere una rotacion y termine volcando. var capsuleInertia = caspsuleShape.CalculateLocalInertia(100000); // Aqui usamos una masa bastante baja (1 Kg) para que cuando se arme el cuerpo rigido y se intente aplicar // un impulso se facil de mover la capsula. var capsuleRigidBodyInfo = new RigidBodyConstructionInfo(1, capsuleMotionState, caspsuleShape, capsuleInertia); var localCapsuleRigidBody = new RigidBody(capsuleRigidBodyInfo); localCapsuleRigidBody.LinearFactor = TGCVector3.One.ToBsVector; localCapsuleRigidBody.SetDamping(0.5f, 0f); localCapsuleRigidBody.Restitution = 0f; localCapsuleRigidBody.Friction = 1; return(localCapsuleRigidBody); }
/// <summary> /// Crea una coleccion de triangulos para Bullet a partir de los triangulos generados por un heighmap /// </summary> /// <param name="triangleDataVB"></param> /// <returns></returns> public static RigidBody CreateSurfaceFromHeighMap(CustomVertex.PositionTextured[] triangleDataVB) { /* * This come from a bullet page * http://www.bulletphysics.org/mediawiki-1.5.8/index.php?title=Code_Snippets * btTriangleMesh *mTriMesh = new btTriangleMesh(); * * while(!done) { * // For whatever your source of triangles is * // give the three points of each triangle: * btVector3 v0(x0,y0,z0); * btVector3 v1(x1,y1,z1); * btVector3 v2(x2,y2,z2); * * // Then add the triangle to the mesh: * mTriMesh->addTriangle(v0,v1,v2); * } * * btCollisionShape *mTriMeshShape = new btBvhTriangleMeshShape(mTriMesh,true); * * // Now use mTriMeshShape as your collision shape. * // Everything else is like a normal rigid body */ /* * Para 1 solo triangulo * var triangle = new Triangle(); * TGCVector3 vector0 = new TGCVector3(0, 0, 0); * TGCVector3 vector1 = new TGCVector3(100, 0, 0); * TGCVector3 vector2 = new TGCVector3(0, 0, 100); * * triangleMesh.AddTriangle(vector0.ToBsVector,vector1.ToBsVector,vector2.ToBsVector,false); */ //Triangulos var triangleMesh = new TriangleMesh(); int i = 0; TGCVector3 vector0; TGCVector3 vector1; TGCVector3 vector2; while (i < triangleDataVB.Length) { var triangle = new Triangle(); vector0 = new TGCVector3(triangleDataVB[i].X, triangleDataVB[i].Y, triangleDataVB[i].Z); vector1 = new TGCVector3(triangleDataVB[i + 1].X, triangleDataVB[i + 1].Y, triangleDataVB[i + 1].Z); vector2 = new TGCVector3(triangleDataVB[i + 2].X, triangleDataVB[i + 2].Y, triangleDataVB[i + 2].Z); i = i + 3; triangleMesh.AddTriangle(vector0.ToBsVector, vector1.ToBsVector, vector2.ToBsVector, false); } CollisionShape meshCollisionShape = new BvhTriangleMeshShape(triangleMesh, true); var meshMotionState = new DefaultMotionState(); var meshRigidBodyInfo = new RigidBodyConstructionInfo(0, meshMotionState, meshCollisionShape); RigidBody meshRigidBody = new RigidBody(meshRigidBodyInfo); return(meshRigidBody); }
/// <summary> /// 剛体を作る /// </summary> /// <param name="collisionShape">剛体の形</param> /// <param name="world">剛体のワールド変換行列</param> /// <param name="rigidProperty">剛体の物性</param> /// <param name="superProperty">物理演算を超越した特性</param> /// <returns></returns> public RigidBody CreateRigidBody(CollisionShape collisionShape, Matrix world, RigidProperty rigidProperty, SuperProperty superProperty) { var mass = superProperty.kinematic ? 0 : rigidProperty.mass; collisionShapes.Add(collisionShape); Vector3 localInertia = new Vector3(0, 0, 0); if (mass != 0) { collisionShape.CalculateLocalInertia(mass, out localInertia); } DefaultMotionState motionState = new DefaultMotionState(world); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia); RigidBody body = new RigidBody(rbInfo); body.Restitution = rigidProperty.restitution; body.Friction = rigidProperty.friction; body.SetDamping(rigidProperty.linear_damp, rigidProperty.angular_damp); float linearDamp = body.LinearDamping; float angularDamp = body.AngularDamping; if (superProperty.kinematic) { body.CollisionFlags = body.CollisionFlags | CollisionFlags.KinematicObject; } body.ActivationState = ActivationState.DisableDeactivation; dynamicsWorld.AddRigidBody(body, superProperty.group, superProperty.mask); return(body); }
public static RigidBody CreateBody(float mass, Matrix startTransform, CollisionShape shape, DynamicsWorld world) { // A body with zero mass is considered static if (mass == 0) { return(CreateStaticBody(startTransform, shape, world)); } // Using a motion state is recommended, // it provides interpolation capabilities and only synchronizes "active" objects var myMotionState = new DefaultMotionState(startTransform); Vector3 localInertia = shape.CalculateLocalInertia(mass); RigidBody body; using (var rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia)) { body = new RigidBody(rbInfo); } if (world != null) { world.AddRigidBody(body); } return(body); }
private RigidBody CreateRigidBody(TGCVector3 position, Vector3 halfSize, float mass) { var boxShape = new BoxShape(halfSize); var transform = TGCMatrix.Translation(position); var motionState = new DefaultMotionState(transform.ToBsMatrix); return(new RigidBody(new RigidBodyConstructionInfo(mass, motionState, boxShape))); }
private void AddRoofRigidBody() { var roofShape = new StaticPlaneShape(TGCVector3.Down.ToBulletVector3(), -3580); var roofMotionState = new DefaultMotionState(); var roofInfo = new RigidBodyConstructionInfo(0, roofMotionState, roofShape); var roofBody = new RigidBody(roofInfo); PhysicalWorld.AddBodyToTheWorld(roofBody); }
public void Init(string MediaDir) { #region Configuracion Basica de World //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3(); #endregion Configuracion Basica de World foreach (var mesh in meshes) { var buildingbody = BulletRigidBodyFactory.Instance.CreateRigidBodyFromTgcMesh(mesh); dynamicsWorld.AddRigidBody(buildingbody); } //Se crea un plano ya que esta escena tiene problemas //con la definición de triangulos para el suelo var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 10); floorShape.LocalScaling = new TGCVector3().ToBulletVector3(); var floorMotionState = new DefaultMotionState(); var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); floorBody.Friction = 1; floorBody.RollingFriction = 1; floorBody.Restitution = 1f; floorBody.UserObject = "floorBody"; dynamicsWorld.AddRigidBody(floorBody); var loader = new TgcSceneLoader(); ///Se crea una caja para que haga las veces del Hummer dentro del modelo físico TgcTexture texture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"\MeshCreator\Scenes\Deposito\Textures\box4.jpg"); TGCBox boxMesh1 = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture); boxMesh1.Position = new TGCVector3(0, 10, 0); hummer = boxMesh1.ToMesh("box"); boxMesh1.Dispose(); //Se crea el cuerpo rígido de la caja, en la definicio de CreateBox el ultimo parametro representa si se quiere o no //calcular el momento de inercia del cuerpo. No calcularlo lo que va a hacer es que la caja que representa el Hummer //no rote cuando colicione contra el mundo. hummerBody = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(55, 20, 80), 10, hummer.Position, 0, 0, 0, 0.55f, false); hummerBody.Restitution = 0; hummerBody.Gravity = new TGCVector3(0, -100, 0).ToBulletVector3(); dynamicsWorld.AddRigidBody(hummerBody); //Se carga el modelo del Hummer hummer = loader.loadSceneFromFile(MediaDir + @"MeshCreator\\Meshes\\Vehiculos\\Hummer\\Hummer-TgcScene.xml").Meshes[0]; leftright = new TGCVector3(1, 0, 0); fowardback = new TGCVector3(0, 0, 1); }
public override void Init(BulletExampleWall ctx) { base.Init(ctx); //Creamos shapes y bodies. //El piso es un plano estatico se dice que si tiene masa 0 es estatico. var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0); var floorMotionState = new DefaultMotionState(); var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); dynamicsWorld.AddRigidBody(floorBody); //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa. var boxShape = new BoxShape(10, 10, 10); var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix; boxTransform.Origin = new TGCVector3(10, 100, 10).ToBulletVector3(); DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform); //Es importante calcular la inercia caso contrario el objeto no rotara. var boxLocalInertia = boxShape.CalculateLocalInertia(1f); var boxInfo = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia); boxBody = new RigidBody(boxInfo); dynamicsWorld.AddRigidBody(boxBody); //Crea una bola de radio 10 origen 50 de 1 kg. var ballShape = new SphereShape(10); var ballTransform = TGCMatrix.Identity; ballTransform.Origin = new TGCVector3(0, 50, 0); var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix); //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien. var ballLocalInertia = ballShape.CalculateLocalInertia(1f); var ballInfo = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia); ballBody = new RigidBody(ballInfo); dynamicsWorld.AddRigidBody(ballBody); //Cargamos objetos de render del framework. var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\granito.jpg"); floorMesh = new TgcPlane(new TGCVector3(-200, 0, -200), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture); var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\madera.jpg"); //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica. boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture); //Se crea una esfera de tamaño 1 para escalarla luego (en render) sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty); //Tgc no crea el vertex buffer hasta invocar a update values. sphereMesh.updateValues(); }
//---------------------------------------------------------------------------------------------- public override void ClientResetScene() { //#ifdef SHOW_NUM_DEEP_PENETRATIONS gNumDeepPenetrationChecks = 0; gNumGjkChecks = 0; //#endif //SHOW_NUM_DEEP_PENETRATIONS gNumClampedCcdMotions = 0; int numObjects = 0; foreach (DiscreteDynamicsWorld world in m_worlds) { // Prefer a better place for this... world.SetDebugDrawer(m_debugDraw); numObjects = world.GetNumCollisionObjects(); IList <CollisionObject> copyArray = world.GetCollisionObjectArray(); for (int i = 0; i < numObjects; i++) { CollisionObject colObj = copyArray[i]; RigidBody body = RigidBody.Upcast(colObj); if (body != null) { if (body.GetMotionState() != null) { DefaultMotionState myMotionState = (DefaultMotionState)body.GetMotionState(); myMotionState.m_graphicsWorldTrans = myMotionState.m_startWorldTrans; body.SetCenterOfMassTransform(ref myMotionState.m_graphicsWorldTrans); colObj.SetInterpolationWorldTransform(ref myMotionState.m_startWorldTrans); if (colObj.GetActivationState() != ActivationState.DISABLE_DEACTIVATION) { colObj.ForceActivationState(ActivationState.ACTIVE_TAG); colObj.Activate(); colObj.SetDeactivationTime(0); } //colObj.setActivationState(WANTS_DEACTIVATION); } //removed cached contact points (this is not necessary if all objects have been removed from the dynamics world) world.GetBroadphase().GetOverlappingPairCache().CleanProxyFromPairs(colObj.GetBroadphaseHandle(), world.GetDispatcher()); if (!body.IsStaticObject()) { IndexedVector3 zero = IndexedVector3.Zero; body.SetLinearVelocity(ref zero); body.SetAngularVelocity(ref zero); } } } ///reset some internal cached data in the broadphase world.GetBroadphase().ResetPool(world.GetDispatcher()); world.GetConstraintSolver().Reset(); } }
private RigidBody CreateBody(float mass, Matrix startTransform, CollisionShape shape, Vector3 localInertia) { var motionState = new DefaultMotionState(startTransform); using (var rbInfo = new RigidBodyConstructionInfo(mass, motionState, shape, localInertia)) { var body = new RigidBody(rbInfo); World.AddRigidBody(body); return(body); } }
public RigidBody(CollisionShape shape, float mass, OpenTK.Matrix4 transform) { DefaultMotionState state = new DefaultMotionState(transform); inertia = shape.BulletShape.CalculateLocalInertia(mass); var info = new RigidBodyConstructionInfo(mass, state, shape.BulletShape, inertia); BulletRigidBody = new BulletSharp.RigidBody(info); BulletRigidBody.UserObject = this; BulletCollisionObject.Restitution = 0.5f; }
public void AddRigidBody(Physics3DRigidBody rb, Components.RigidBodyDesc desc) { MotionState motionState; Matrix4x4 mat = MatrixExt.Transform(desc.Position, desc.Rotation); rb.defaultPosition = desc.Position; rb.defaultRotation = desc.Rotation; motionState = new DefaultMotionState(GetMatrix(mat)); CollisionShape collisionShape; switch (desc.Shape) { case Components.RigidBodyShape.Sphere: collisionShape = new SphereShape(desc.Dimemsions.X); break; case Components.RigidBodyShape.Capsule: collisionShape = new CapsuleShape(desc.Dimemsions.X, desc.Dimemsions.Y); break; case Components.RigidBodyShape.Box: default: collisionShape = new BoxShape(GetVector3(desc.Dimemsions)); break; } float mass = desc.Mass; BulletSharp.Math.Vector3 localInertia = new BulletSharp.Math.Vector3(); if (desc.Type == 0) { mass = 0; } else { collisionShape.CalculateLocalInertia(mass, out localInertia); } var rigidbodyInfo = new RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia); rigidbodyInfo.Friction = desc.Friction; rigidbodyInfo.LinearDamping = desc.LinearDamping; rigidbodyInfo.AngularDamping = desc.AngularDamping; rigidbodyInfo.Restitution = desc.Restitution; rb.rigidBody = new RigidBody(rigidbodyInfo); rb.rigidBody.ActivationState = ActivationState.DisableDeactivation; rb.rigidBody.SetSleepingThresholds(0, 0); if (desc.Type == Components.RigidBodyType.Kinematic) { rb.rigidBody.CollisionFlags |= CollisionFlags.KinematicObject; } world.AddRigidBody(rb.rigidBody, 1 << desc.CollisionGroup, desc.CollisionMask); }
public static RigidBody crearBodyEsfericoEstatico(TGCVector3 origen, float radio) { #region BOLA var ballShape = new SphereShape(radio); var ballTransform = TGCMatrix.Identity; ballTransform.Origin = origen; var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix); var ballInfo = new RigidBodyConstructionInfo(0, ballMotionState, ballShape); return(new RigidBody(ballInfo)); #endregion }
private static RigidBody CreateRigidBody(TGCVector3 position, float mass, CapsuleShape capsule) { var inertia = capsule.CalculateLocalInertia(mass); var transform = TGCMatrix.Translation(position); var motionState = new DefaultMotionState(transform.ToBsMatrix); var rigidBodyInfo = new RigidBodyConstructionInfo(mass, motionState, capsule, inertia); return(new RigidBody(rigidBodyInfo) { AngularFactor = Vector3.UnitY }); }