Ejemplo n.º 1
0
        public void UpdateAction(CollisionWorld collisionWorld, float deltaTimeStep)
        {
            _findGroundAndSteps.Reset();
            collisionWorld.ContactTest(RigidBody, _findGroundAndSteps);
            OnGround      = _findGroundAndSteps.HaveGround;
            _groundNormal = _findGroundAndSteps.GroundNormal;

            UpdateVelocity(deltaTimeStep);
            if (_stepping || _findGroundAndSteps.HaveStep)
            {
                if (!_stepping)
                {
                    _steppingTo        = _findGroundAndSteps.StepPoint;
                    _steppingInvNormal = _findGroundAndSteps.getInvNormal();
                }
                StepUp(deltaTimeStep);
            }

            if (OnGround || _stepping)
            {
                /* Avoid going down on ramps, if already on ground, and clearGravity()
                 * is not enough */
                RigidBody.Gravity = Vector3.Zero;
            }
            else
            {
                RigidBody.Gravity = _gravity;
            }
        }
Ejemplo n.º 2
0
    public 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);

        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
        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

        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.ActiveTag;
        }
        rbInfo.Dispose();

        world.AddRigidBody(body);

        return(body);
    }
Ejemplo n.º 3
0
    static Vector3 ParallelComponent(ref Vector3 direction, ref Vector3 normal)
    {
        float magnitude;

        Vector3.Dot(ref direction, ref normal, out magnitude);
        return(normal * magnitude);
    }
Ejemplo n.º 4
0
        // Update is called once per frame
        public void Update()
        {
            lock (lck)
            {
                if (mustUpdateTransform)
                {
                    UnityEngine.Vector3    position = BSExtensionMethods2.ExtractTranslationFromMatrix(ref lastBulletTransform.Transform);
                    UnityEngine.Quaternion rotation = BSExtensionMethods2.ExtractRotationFromMatrix(ref lastBulletTransform.Transform);
                    // Interpolation is needed in threaded mode
                    // Maybe we can have a call to the physics engine in an update method instead ?
                    if (threadHelper != null && previousBulletTransform != null)
                    {
                        double currentTime = threadHelper.TotalSimulationTime;
                        UnityEngine.Vector3    previousPosition = BSExtensionMethods2.ExtractTranslationFromMatrix(ref previousBulletTransform.Transform);
                        UnityEngine.Quaternion previousRotation = BSExtensionMethods2.ExtractRotationFromMatrix(ref previousBulletTransform.Transform);

                        double interpolationFactor = (currentTime - lastBulletTransform.TimeStamp) / (lastBulletTransform.TimeStamp - previousBulletTransform.TimeStamp);

                        transform.position = UnityEngine.Vector3.LerpUnclamped(previousPosition, position, (float)interpolationFactor);
                        transform.rotation = UnityEngine.Quaternion.SlerpUnclamped(previousRotation, rotation, (float)interpolationFactor);
                    }
                    else
                    {
                        transform.position = position;
                        transform.rotation = rotation;
                    }
                    mustUpdateTransform = false;
                }
                pos = transform.position.ToBullet();
                rot = transform.rotation.ToBullet();
            }
        }
    //Think this is supposed doing the move and slide Riley reffered to.
    protected void UpdateTargetPositionBasedOnCollision(ref Vector3 hitNormal, float tangentMag, float normalMag)
    {
        Vector3 movementDirection = targetPosition - currentPosition;
        float   movementLength    = movementDirection.Length;

        if (movementLength > MathUtil.SIMD_EPSILON)
        {
            movementDirection.Normalize();

            Vector3 reflectDir = ComputeReflectionDirection(ref movementDirection, ref hitNormal);
            reflectDir.Normalize();

            Vector3 perpindicularDir;

            perpindicularDir = PerpindicularComponent(ref reflectDir, ref hitNormal);

            targetPosition = currentPosition;

            if (normalMag != 0.0f)
            {
                Vector3 perpComponent = perpindicularDir * (normalMag * movementLength);
                targetPosition += perpComponent;
            }
        }
    }
Ejemplo n.º 6
0
 public BGameObjectMotionState(Transform transform)
 {
     this.transform = transform;
     pos            = transform.position.ToBullet();
     rot            = transform.rotation.ToBullet();
     threadHelper   = BPhysicsWorld.Get().PhysicsWorldHelper as BThreadedWorldHelper;
 }
Ejemplo n.º 7
0
        public void CheckGround(ManifoldPoint cp)
        {
            if (HaveGround)
            {
                return;
            }

            Matrix inverse = _controller.RigidBody.WorldTransform;

            inverse.Invert();
            Vector3 localPoint = Vector3.TransformCoordinate(cp.PositionWorldOnB, inverse);

            localPoint = new Vector3(localPoint.X, localPoint.Y + _controller.CapsuleHalfHeight, localPoint.Z);

            float r        = localPoint.Length;
            float cosTheta = localPoint.Y / r;

            if (System.Math.Abs(r - _controller.CapsuleRadius) <= _controller.GroundSearchMargin &&
                cosTheta < _controller.MaxCosGround)
            {
                HaveGround   = true;
                GroundPoint  = cp.PositionWorldOnB;
                GroundNormal = cp.NormalWorldOnB;
            }
        }
Ejemplo n.º 8
0
 public override void DrawTriangle(ref BM.Vector3 v0, ref BM.Vector3 v1, ref BM.Vector3 v2, ref BM.Vector3 color, float alpha)
 {
     Gizmos.color = new Color(color.X, color.Y, color.Z);
     Gizmos.DrawLine(v0.ToUnity(), v1.ToUnity());
     Gizmos.DrawLine(v1.ToUnity(), v2.ToUnity());
     Gizmos.DrawLine(v2.ToUnity(), v0.ToUnity());
 }
Ejemplo n.º 9
0
 public override void DrawLine(ref BM.Vector3 from, ref BM.Vector3 to, ref BM.Vector3 fromColor, ref BM.Vector3 toColor)
 {
     /* org
      * UnityEngine.Gizmos.color = new UnityEngine.Color(fromColor.X, fromColor.Y, fromColor.Z);
      * UnityEngine.Gizmos.DrawLine(from.ToUnity(), to.ToUnity());
      */
 }
Ejemplo n.º 10
0
 public override void DrawSphere(ref BM.Vector3 p, float radius, ref BM.Vector3 color)
 {
     /* org
      * UnityEngine.Color c = new UnityEngine.Color(color.X, color.Y, color.Z);
      * BUtility.DebugDrawSphere(p.ToUnity(),UnityEngine.Quaternion.identity,UnityEngine.Vector3.one, UnityEngine.Vector3.one * radius, c);
      */
 }
Ejemplo n.º 11
0
 public override void DrawBox(ref BM.Vector3 bbMin, ref BM.Vector3 bbMax, ref BM.Vector3 color)
 {
     UnityEngine.Bounds b = new UnityEngine.Bounds(bbMin.ToUnity(), UnityEngine.Vector3.zero);
     b.Encapsulate(bbMax.ToUnity());
     UnityEngine.Gizmos.color = new UnityEngine.Color(color.X, color.Y, color.Z);
     UnityEngine.Gizmos.DrawWireCube(b.center, b.size);
 }
Ejemplo n.º 12
0
    static Vector3 ComputeReflectionDirection(ref Vector3 direction, ref Vector3 normal)
    {
        float dot;

        Vector3.Dot(ref direction, ref normal, out dot);
        return(direction - (2.0f * dot) * normal);
    }
Ejemplo n.º 13
0
        public static Vector3 Cast(this BM.Vector3 vec)
        {
            var output = new Vector3();

            *(BM.Vector3 *)&output = vec;
            return(output);
        }
Ejemplo n.º 14
0
    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);
    }
Ejemplo n.º 15
0
        public override void DrawArc(ref BM.Vector3 center, ref BM.Vector3 normal, ref BM.Vector3 axis, float radiusA, float radiusB, float minAngle, float maxAngle,
                                     ref BM.Vector3 color, bool drawSect, float stepDegrees)
        {
            var col = new Color(color.X, color.Y, color.Z);

            BUtility.DebugDrawArc(center.ToUnity(), normal.ToUnity(), axis.ToUnity(), radiusA, radiusB, minAngle, maxAngle, col, drawSect, stepDegrees);
        }
Ejemplo n.º 16
0
        public Vector3 getInvNormal()
        {
            if (!HaveStep)
            {
                return(new  Vector3(0, 0, 0));
            }

            /*
             * Original code
             * btMatrix3x3 frame;
             * // Build it as step to world
             * frame[2].setValue(0, 0, 1);
             * frame[1] = mStepNormal;
             * frame[0] = frame[1].cross(frame[2]);
             * frame[0].normalize();
             * // Convert it to world to step
             * frame = frame.transpose();
             * return frame[1];
             */

            Matrix frame = Matrix.Zero;

            // Build it as step to world
            frame.Column3 = new Vector4(0, 0, 1, 0);
            frame.Column2 = new Vector4(_stepNormal, 0);
            var crossed = Vector3.Cross(
                new Vector3(frame.Column2.X, frame.Column2.Y, frame.Column2.Z),
                new Vector3(frame.Column3.X, frame.Column3.Y, frame.Column3.Z));

            frame.Column1 = new Vector4(crossed.X, crossed.Y, crossed.Z, 0);
            frame.Column1.Normalize();
            // Convert it to world to step
            frame.Transpose();
            return(new Vector3(frame.Column2.X, frame.Column2.Y, frame.Column2.Z));
        }
Ejemplo n.º 17
0
        public static Collider CreateDynamicCollider(CollisionShape shape, float mass, Matrix startTransform = default)
        {
            Vector3   localInertia = shape.CalculateLocalInertia(mass);
            RigidBody body         = CreateBody(mass, startTransform, shape, localInertia);

            return(Collider.Create(body));
        }
Ejemplo n.º 18
0
        public static Collider CreateStaticCollider(CollisionShape shape, Matrix startTransform = default)
        {
            Vector3   localInertia = Vector3.Zero;
            RigidBody body         = CreateBody(0, startTransform, shape, localInertia);

            return(Collider.Create(body));
        }
Ejemplo n.º 19
0
    /// <summary>
    /// Allows the user to select a robot node with their mouse and change the intake/release node
    /// </summary>
    /// <param name="index">configuring index</param>
    public void SetMechanism(int index)
    {
        //Casts a ray from the camera in the direction the mouse is in and returns the closest object hit
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        BulletSharp.Math.Vector3 start = ray.origin.ToBullet();
        BulletSharp.Math.Vector3 end   = ray.GetPoint(200).ToBullet();

        //Creates a callback result that will be updated if we do a ray test with it
        ClosestRayResultCallback rayResult = new ClosestRayResultCallback(ref start, ref end);

        //Retrieves the bullet physics world and does a ray test with the given coordinates and updates the callback object
        BPhysicsWorld world = BPhysicsWorld.Get();

        world.world.RayTest(start, end, rayResult);

        //If there is a collision object and it is dynamic and not a robot part, change the gamepiece to that
        if (rayResult.CollisionObject != null)
        {
            GameObject collisionObject = (rayResult.CollisionObject.UserObject as BRigidBody).gameObject;
            if (rayResult.CollisionObject.CollisionFlags == BulletSharp.CollisionFlags.StaticObject)
            {
                UserMessageManager.Dispatch("Please click on a robot part", 3);
            }
            else if (collisionObject == null)
            {
                Debug.Log("DPM: Game object not found");
            }
            else if (collisionObject.transform.parent == transform)
            {
                if (definingIntake)
                {
                    intakeNode[index] = collisionObject;
                    SetInteractor(intakeNode[index], index);

                    UserMessageManager.Dispatch(collisionObject.name + " has been selected as intake node", 5);

                    definingIntake = false;
                }
                else
                {
                    releaseNode[index] = collisionObject;
                    SetInteractor(releaseNode[index], index);

                    UserMessageManager.Dispatch(collisionObject.name + " has been selected as release node", 5);

                    definingRelease = false;
                }

                RevertNodeColors(hoveredNode, hoveredColors);
            }
            else
            {
                UserMessageManager.Dispatch("A gamepiece is NOT a robot part!", 3);
            }
        }
        else
        {
        }
    }
        public override void Draw3dText(ref BM.Vector3 location, String textString)
        {
#if UNITY_EDITOR
            UnityEditor.Handles.Label(location.ToUnity(), textString);
#else
            Debug.LogError("Not implemented");
#endif
        }
Ejemplo n.º 21
0
 public override void DrawTriangle(ref BM.Vector3 v0, ref BM.Vector3 v1, ref BM.Vector3 v2, ref BM.Vector3 n0, ref BM.Vector3 n1, ref BM.Vector3 n2, ref BM.Vector3 color, float alpha)
 {
     //todo normals and alpha
     UnityEngine.Gizmos.color = new UnityEngine.Color(color.X, color.Y, color.Z);
     UnityEngine.Gizmos.DrawLine(v0.ToUnity(), v1.ToUnity());
     UnityEngine.Gizmos.DrawLine(v1.ToUnity(), v2.ToUnity());
     UnityEngine.Gizmos.DrawLine(v2.ToUnity(), v0.ToUnity());
 }
Ejemplo n.º 22
0
 public override void DrawSphere(float radius, ref BM.Matrix trans, ref BM.Vector3 color)
 {
     UnityEngine.Vector3    pos   = BSExtensionMethods2.ExtractTranslationFromMatrix(ref trans);
     UnityEngine.Quaternion rot   = BSExtensionMethods2.ExtractRotationFromMatrix(ref trans);
     UnityEngine.Vector3    scale = BSExtensionMethods2.ExtractScaleFromMatrix(ref trans);
     UnityEngine.Color      c     = new UnityEngine.Color(color.X, color.Y, color.Z);
     BUtility.DebugDrawSphere(pos, rot, scale, UnityEngine.Vector3.one * radius, c);
 }
Ejemplo n.º 23
0
 public void ResetStatus()
 {
     _targetSpeed      = new Vector3(0, 0, 0);
     _isJumping        = false;
     OnGround          = false;
     RigidBody.Gravity = _gravity;
     CancelStep();
 }
Ejemplo n.º 24
0
 public override void DrawPlane(ref BM.Vector3 planeNormal, float planeConst, ref BM.Matrix trans, ref BM.Vector3 color)
 {
     UnityEngine.Vector3    pos   = BSExtensionMethods2.ExtractTranslationFromMatrix(ref trans);
     UnityEngine.Quaternion rot   = BSExtensionMethods2.ExtractRotationFromMatrix(ref trans);
     UnityEngine.Vector3    scale = BSExtensionMethods2.ExtractScaleFromMatrix(ref trans);
     UnityEngine.Color      c     = new UnityEngine.Color(color.X, color.Y, color.Z);
     BUtility.DebugDrawPlane(pos, rot, scale, planeNormal.ToUnity(), planeConst, c);
 }
Ejemplo n.º 25
0
 public override void DrawBox(ref BM.Vector3 bbMin, ref BM.Vector3 bbMax, ref BM.Matrix trans, ref BM.Vector3 color)
 {
     UnityEngine.Vector3    pos   = BSExtensionMethods2.ExtractTranslationFromMatrix(ref trans);
     UnityEngine.Quaternion rot   = BSExtensionMethods2.ExtractRotationFromMatrix(ref trans);
     UnityEngine.Vector3    scale = BSExtensionMethods2.ExtractScaleFromMatrix(ref trans);
     UnityEngine.Vector3    size  = (bbMax - bbMin).ToUnity() / 2;
     UnityEngine.Color      c     = new UnityEngine.Color(color.X, color.Y, color.Z);
     BUtility.DebugDrawBox(pos, rot, scale, size, c);
 }
Ejemplo n.º 26
0
        public override void SetGravityDirection(Vector3 direction)
        {
            var d = Vector3.Normalize(direction);

            _gravityDirection = d;
            var gravity = _gravityDirection * _gravityStrength * 10.0f;

            _world.SetGravity(ref gravity);
        }
    protected void SaveFinalState()
    {
        m_comf = m_rb.CenterOfMassPosition;
        Matrix curTrans = m_rb.WorldTransform;

        m_posf      = BSExtensionMethods2.ExtractTranslationFromMatrix(ref curTrans);
        m_rotf      = BSExtensionMethods2.ExtractRotationFromMatrix(ref curTrans);
        m_eulerrotf = m_rotf.eulerAngles;
    }
Ejemplo n.º 28
0
        public override void DrawSphere(float radius, ref BM.Matrix trans, ref BM.Vector3 color)
        {
            var pos   = BulletExtensionMethods.ExtractTranslationFromMatrix(ref trans);
            var rot   = BulletExtensionMethods.ExtractRotationFromMatrix(ref trans);
            var scale = BulletExtensionMethods.ExtractScaleFromMatrix(ref trans);
            var c     = new Color(color.X, color.Y, color.Z);

            BUtility.DebugDrawSphere(pos, rot, scale, Vector3.one * radius, c);
        }
Ejemplo n.º 29
0
        public override void DrawPlane(ref BM.Vector3 planeNormal, float planeConst, ref BM.Matrix trans, ref BM.Vector3 color)
        {
            var pos   = BulletExtensionMethods.ExtractTranslationFromMatrix(ref trans);
            var rot   = BulletExtensionMethods.ExtractRotationFromMatrix(ref trans);
            var scale = BulletExtensionMethods.ExtractScaleFromMatrix(ref trans);
            var c     = new Color(color.X, color.Y, color.Z);

            BUtility.DebugDrawPlane(pos, rot, scale, planeNormal.ToUnity(), planeConst, c);
        }
        public override void DrawBox(ref BM.Vector3 bbMin, ref BM.Vector3 bbMax, ref BM.Vector3 color)
        {
            Bounds b = new Bounds(bbMin.ToUnity(), Vector3.zero);

            b.Encapsulate(bbMax.ToUnity());
            Gizmos.matrix = Matrix4x4.identity;
            Gizmos.color  = new Color(color.X, color.Y, color.Z);
            Gizmos.DrawWireCube(b.center, b.size);
        }
    //IMPORTANT Time.fixedTime must match the timestep being used here.
    public static List<UnityEngine.Vector3> SimulateBall(BRigidBody ballRb, UnityEngine.Vector3 ballThrowForce, int numberOfSimulationSteps, bool reverseOrder)
    {
        var ballPositions = new List<UnityEngine.Vector3>(numberOfSimulationSteps);

        //Create a World
        Debug.Log("Initialize physics");

        CollisionConfiguration CollisionConf;
        CollisionDispatcher Dispatcher;
        BroadphaseInterface Broadphase;
        CollisionWorld cw;
        SequentialImpulseConstraintSolver Solver;
        BulletSharp.SoftBody.SoftBodyWorldInfo softBodyWorldInfo;

        //This should create a copy of the BPhysicsWorld with the same settings
        BPhysicsWorld bw = BPhysicsWorld.Get();
        bw.CreatePhysicsWorld(out cw, out CollisionConf, out Dispatcher, out Broadphase, out Solver, out softBodyWorldInfo);
        World = (DiscreteDynamicsWorld) cw;

        //Copy all existing rigidbodies in scene
        // IMPORTANT rigidbodies must be added to the offline world in the same order that they are in the source world
        // this is because collisions must be resolved in the same order for the sim to be deterministic
        DiscreteDynamicsWorld sourceWorld = (DiscreteDynamicsWorld) bw.world;
        BulletSharp.RigidBody bulletBallRb = null;
        BulletSharp.Math.Matrix mm = BulletSharp.Math.Matrix.Identity;
        for(int i = 0; i < sourceWorld.NumCollisionObjects; i++)
        {
            CollisionObject co = sourceWorld.CollisionObjectArray[i];
            if (co != null && co.UserObject is BRigidBody)
            {
                BRigidBody rb = (BRigidBody) co.UserObject;
                float mass = rb.isDynamic() ? rb.mass : 0f;
                BCollisionShape existingShape = rb.GetComponent<BCollisionShape>();
                CollisionShape shape = null;
                if (existingShape is BSphereShape)
                {
                    shape = ((BSphereShape)existingShape).CopyCollisionShape();
                }
                else if (existingShape is BBoxShape)
                {
                    shape = ((BBoxShape)existingShape).CopyCollisionShape();
                }

                RigidBody bulletRB = null;
                BulletSharp.Math.Vector3 localInertia = new BulletSharp.Math.Vector3();
                rb.CreateOrConfigureRigidBody(ref bulletRB, ref localInertia, shape, null);
                BulletSharp.Math.Vector3 pos = rb.GetCollisionObject().WorldTransform.Origin;
                BulletSharp.Math.Quaternion rot = rb.GetCollisionObject().WorldTransform.GetOrientation();
                BulletSharp.Math.Matrix.AffineTransformation(1f, ref rot, ref pos, out mm);
                bulletRB.WorldTransform = mm;
                World.AddRigidBody(bulletRB, rb.groupsIBelongTo, rb.collisionMask);
                if (rb == ballRb)
                {
                    bulletBallRb = bulletRB;
                    bulletRB.ApplyCentralImpulse(ballThrowForce.ToBullet());
                }
            }
        }

        //Step the simulation numberOfSimulationSteps times
        for (int i = 0; i < numberOfSimulationSteps; i++)
        {
            int numSteps = World.StepSimulation(1f / 60f, 10, 1f / 60f);
            ballPositions.Add(bulletBallRb.WorldTransform.Origin.ToUnity());
        }

        UnityEngine.Debug.Log("ExitPhysics");
        if (World != null)
        {
            //remove/dispose constraints
            int i;
            for (i = World.NumConstraints - 1; i >= 0; i--)
            {
                TypedConstraint constraint = World.GetConstraint(i);
                World.RemoveConstraint(constraint);
                constraint.Dispose();
            }

            //remove the rigidbodies from the dynamics world and delete them
            for (i = World.NumCollisionObjects - 1; i >= 0; i--)
            {
                CollisionObject obj = World.CollisionObjectArray[i];
                RigidBody body = obj as RigidBody;
                if (body != null && body.MotionState != null)
                {
                    body.MotionState.Dispose();
                }
                World.RemoveCollisionObject(obj);
                obj.Dispose();
            }

            World.Dispose();
            Broadphase.Dispose();
            Dispatcher.Dispose();
            CollisionConf.Dispose();
        }

        if (Broadphase != null)
        {
            Broadphase.Dispose();
        }
        if (Dispatcher != null)
        {
            Dispatcher.Dispose();
        }
        if (CollisionConf != null)
        {
            CollisionConf.Dispose();
        }

        return ballPositions;
    }
Ejemplo n.º 32
0
        //called by Physics World just before rigid body is added to world.
        //the current rigid body properties are used to rebuild the rigid body.
        internal override bool _BuildCollisionObject()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();
            if (m_rigidBody != null) {
                if (isInWorld && world != null) {
                    isInWorld = false;
                    world.RemoveRigidBody(m_rigidBody);
                }
            }

            if (transform.localScale != UnityEngine.Vector3.one) {
                BDebug.LogError(debugType, "The local scale on this rigid body is not one. Bullet physics does not support scaling on a rigid body world transform. Instead alter the dimensions of the CollisionShape.");
            }

            m_collisionShape = GetComponent<BCollisionShape>();
            if (m_collisionShape == null) {
                BDebug.LogError(debugType, "There was no collision shape component attached to this BRigidBody. {0}", name);
                return false;
            }

            CollisionShape cs = m_collisionShape.GetCollisionShape();
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            _localInertia = BulletSharp.Math.Vector3.Zero;
            if (isDynamic()) {
                cs.CalculateLocalInertia(_mass, out _localInertia);
            }

            if (m_rigidBody == null) {
                m_motionState = new BGameObjectMotionState(transform);
                float bulletMass = _mass;
                if (!isDynamic())
                {
                    bulletMass = 0f;
                }

                RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(bulletMass, m_motionState, cs, _localInertia);
                rbInfo.Friction = _friction;
                rbInfo.RollingFriction = _rollingFriction;
                rbInfo.LinearDamping = _linearDamping;
                rbInfo.AngularDamping = _angularDamping;
                rbInfo.Restitution = _restitution;
                rbInfo.LinearSleepingThreshold = _linearSleepingThreshold;
                rbInfo.AngularSleepingThreshold = _angularSleepingThreshold;
                rbInfo.AdditionalDamping = _additionalDamping;
                rbInfo.AdditionalAngularDampingFactor = _additionalAngularDampingFactor;
                rbInfo.AdditionalAngularDampingThresholdSqr = _additionalAngularDampingThresholdSqr;
                rbInfo.AdditionalDampingFactor = _additionalDampingFactor;
                rbInfo.AdditionalLinearDampingThresholdSqr = _additionalLinearDampingThresholdSqr;
                m_rigidBody = new RigidBody(rbInfo);
                m_rigidBody.UserObject = this;
                m_rigidBody.AngularVelocity = _angularVelocity.ToBullet();
                m_rigidBody.LinearVelocity = _linearVelocity.ToBullet();
                rbInfo.Dispose();
            } else {
                float usedMass = 0f;
                if (isDynamic())
                {
                    usedMass = _mass;
                }
                m_rigidBody.SetMassProps(usedMass, _localInertia);
                m_rigidBody.Friction = _friction;
                m_rigidBody.RollingFriction = _rollingFriction;
                m_rigidBody.SetDamping(_linearDamping,_angularDamping);
                m_rigidBody.Restitution = _restitution;
                m_rigidBody.SetSleepingThresholds(_linearSleepingThreshold, _angularSleepingThreshold);
                m_rigidBody.AngularVelocity = _angularVelocity.ToBullet();
                m_rigidBody.LinearVelocity = _linearVelocity.ToBullet();
                m_rigidBody.CollisionShape = cs;

            }
            m_rigidBody.CollisionFlags = m_collisionFlags;
            m_rigidBody.LinearFactor = _linearFactor.ToBullet();
            m_rigidBody.AngularFactor = _angularFactor.ToBullet();

            //if kinematic then disable deactivation
            if ((m_collisionFlags & BulletSharp.CollisionFlags.KinematicObject) != 0) {
                m_rigidBody.ActivationState = ActivationState.DisableDeactivation;
            }
            return true;
        }
Ejemplo n.º 33
0
        //called by Physics World just before rigid body is added to world.
        //the current rigid body properties are used to rebuild the rigid body.
        internal bool _BuildRigidBody()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();
            if (m_Brigidbody != null) {
                if (isInWorld && world != null) {
                    isInWorld = false;
                    world.RemoveRigidBody(m_Brigidbody);
                }
            }

            if (transform.localScale != UnityEngine.Vector3.one) {
                Debug.LogError("The local scale on this rigid body is not one. Bullet physics does not support scaling on a rigid body world transform. Instead alter the dimensions of the CollisionShape.");
            }

            m_collisionShape = GetComponent<BCollisionShape>();
            if (m_collisionShape == null) {
                Debug.LogError("There was no collision shape component attached to this BRigidBody. " + name);
                return false;
            }

            CollisionShape cs = m_collisionShape.GetCollisionShape();
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            _localInertia = BulletSharp.Math.Vector3.Zero;
            if (_type == RBType.dynamic) {
                cs.CalculateLocalInertia(_mass, out _localInertia);
            }

            if (m_Brigidbody == null) {
                m_motionState = new BGameObjectMotionState(transform);
                RigidBodyConstructionInfo rbInfo;
                if (_type == RBType.dynamic) {
                    rbInfo = new RigidBodyConstructionInfo(_mass, m_motionState, cs, _localInertia);
                } else {
                    rbInfo = new RigidBodyConstructionInfo(0, m_motionState, cs, localInertia);
                }
                m_Brigidbody = new RigidBody(rbInfo);
                rbInfo.Dispose();
            } else {
                m_Brigidbody.SetMassProps(_mass, localInertia);
                m_Brigidbody.CollisionShape = cs;
            }

            if (_type == RBType.kinematic) {
                m_Brigidbody.CollisionFlags = m_Brigidbody.CollisionFlags | BulletSharp.CollisionFlags.KinematicObject;
                m_Brigidbody.ActivationState = ActivationState.DisableDeactivation;
            }
            if (_isTrigger)
            {
                m_Brigidbody.CollisionFlags = m_Brigidbody.CollisionFlags | BulletSharp.CollisionFlags.NoContactResponse;
            }
            return true;
        }