Пример #1
0
        /// <summary>
        /// Sweeps a convex shape against the physics world reporting all hits on the path that are not ignored by the filter, beware convex sweeps can be very costly especially if they are long
        /// </summary>
        /// <param name="shape">Shape to sweep</param>
        /// <param name="startPos">Location to start the sweep from</param>
        /// <param name="rotation">Rotation of the shape during the sweep</param>
        /// <param name="sweep">Direction in which to sweep, the length of the vector is the length of the sweep</param>
        /// <param name="sweepRules">Collision rules to filter the sweep hits, anything above "NoSolver" is ignored</param>
        /// <param name="outSweepResults">All overlaps on the sweep path</param>
        /// <returns>True if any object was hit</returns>
        public bool MultiSweep(ConvexShape shape, ref SharpDX.Vector3 startPos, ref SharpDX.Quaternion rotation, ref SharpDX.Vector3 sweep, CollisionRules sweepRules, List <SRaycastResult> outSweepResults)
        {
            SimpleCollisionRulesOwner rulesOwner     = new SimpleCollisionRulesOwner(sweepRules);
            RigidTransform            startTransform = new RigidTransform(startPos.ToBepu(), rotation.ToBepu());
            Vector3 sweepVector = sweep.ToBepu();
            List <RayCastResult> physicsResults = new List <RayCastResult>();

            if (m_physicSpace.ConvexCast(shape, ref startTransform, ref sweepVector, GetOverlapFilter(rulesOwner), physicsResults))
            {
                foreach (RayCastResult physicsResult in physicsResults)
                {
                    if (physicsResult.HitObject.Tag is CEntity gameEntity)
                    {
                        CollisionRule  rule       = CollisionRules.GetCollisionRule(physicsResult.HitObject, rulesOwner);
                        SRaycastResult gameResult = new SRaycastResult()
                        {
                            HitEntity   = gameEntity,
                            Location    = physicsResult.HitData.Location.ToSharp(),
                            Normal      = -physicsResult.HitData.Normal.ToSharp(),
                            Distance    = physicsResult.HitData.T,
                            bIsSolidHit = rule <= CollisionRule.Normal
                        };
                        outSweepResults.Add(gameResult);
                    }
                }
                return(outSweepResults.Count > 0);
            }

            return(false);
        }
Пример #2
0
        /// <summary>
        /// Returns all overlapping objects of a given ray with the physics world, the ray does NOT stop at solid hit but will report all overlaps and solid hits on the ray
        /// </summary>
        /// <param name="ray">Ray to test against</param>
        /// <param name="length">Maximum distance to test</param>
        /// <param name="rayRules">Collision Rules to use for the ray anything above "NoSolver" is ignored</param>
        /// <param name="outResults">All overlaps on the ray</param>
        /// <returns>True if any object was hit</returns>
        public bool RayOverlap(ref Ray ray, float length, CollisionRules rayRules, List <SRaycastResult> outResults)
        {
            SimpleCollisionRulesOwner rulesOwner     = new SimpleCollisionRulesOwner(rayRules);
            List <RayCastResult>      physicsResults = new List <RayCastResult>();

            if (m_physicSpace.RayCast(ray.ToBepu(), length, GetOverlapFilter(rulesOwner), physicsResults))
            {
                foreach (RayCastResult physicsResult in physicsResults)
                {
                    if (physicsResult.HitObject.Tag is CEntity gameEntity)
                    {
                        CollisionRule  rule       = CollisionRules.GetCollisionRule(physicsResult.HitObject, rulesOwner);
                        SRaycastResult gameResult = new SRaycastResult()
                        {
                            HitEntity   = gameEntity,
                            Location    = physicsResult.HitData.Location.ToSharp(),
                            Normal      = physicsResult.HitData.Normal.ToSharp(),
                            Distance    = physicsResult.HitData.T,
                            bIsSolidHit = rule <= CollisionRule.Normal
                        };
                        outResults.Add(gameResult);
                    }
                }
                return(outResults.Count > 0);
            }

            return(false);
        }
Пример #3
0
        protected void TryToAdd(EntityCollidable collidable)
        {
            CollisionRule rule;

            if ((rule = CollisionRules.collisionRuleCalculator(DetectorVolume, collidable)) <
                CollisionRule.NoNarrowPhasePair)
            {
                //Clamp the rule to the parent's rule.  Always use the more restrictive option.
                //Don't have to test for NoNarrowPhasePair rule on the parent's rule because then the parent wouldn't exist!
                if (rule < CollisionRule)
                {
                    rule = CollisionRule;
                }

                if (!subPairs.ContainsKey(collidable))
                {
                    DetectorVolumePairHandler newPair =
                        NarrowPhaseHelper.GetPairHandler(DetectorVolume, collidable, rule) as DetectorVolumePairHandler;
                    if (newPair != null)
                    {
                        newPair.Parent = this;
                        subPairs.Add(collidable, newPair);
                    }
                }

                containedPairs.Add(collidable);
            }
        }
Пример #4
0
 protected override void CollisionRulesUpdated()
 {
     foreach (var pair in pairs.Values)
     {
         pair.CollisionRule = CollisionRules.CollisionRuleCalculator(pair.BroadPhaseOverlap.entryA, pair.BroadPhaseOverlap.entryB);
     }
 }
Пример #5
0
        protected void CheckCollisionFor(ICollidableObject primary, ICollidableObject secondary)
        {
            CollisionRuleEntry collisionRule;

            if (CollisionRules.CanCollide(primary.CollisionClass, secondary.CollisionClass, out collisionRule))
            {
                ICollisionLifetimeEntry collisionEntry = null;
                //Check the collision lifetime tracker.  If there is already a collision lifetime entry being tracked, do nothing and return.
                if (_collisionLifetimes.Contains(primary, secondary, out collisionEntry))
                {
                    //The specified entities have collided before.  Check to see if this collision time is last the cooldown period
                    if ((collisionRule != null) &&
                        !collisionEntry.CanCollideAgain(collisionRule.Cooldown, Globals.TotalGameTimeSeconds))
                    {
                        return;
                    }
                }

                if (CollisionChecker.AreInCollision(primary, secondary))
                {
                    if (collisionRule == null || collisionRule.TrackLifeTime)
                    {
                        _collisionLifetimes.Add(primary, secondary, Globals.TotalGameTimeSeconds);
                    }
                    _onCollision.Notify(new CollisionEventArgs(primary, secondary));
                }
            }
        }
Пример #6
0
 protected override void CollisionRulesUpdated()
 {
     for (int i = 0; i < pairs.Count; i++)
     {
         pairs[i].CollisionRule = CollisionRules.CollisionRuleCalculator(pairs[i].BroadPhaseOverlap.entryA.collisionRules, pairs[i].BroadPhaseOverlap.entryB.collisionRules);
     }
 }
Пример #7
0
        public Tread(Entity tankBody, Vector3 offsetToFrontOfTread, int segmentCount, Fix64 spacing, TreadSegmentDescription treadSegmentDescription)
        {
            Segments = new List <TreadSegment>();
            Vector3 nextSegmentPosition = tankBody.Position + offsetToFrontOfTread;

            //The front of the tread includes the radius of the first segment.
            nextSegmentPosition.Z += treadSegmentDescription.Radius * (Fix64)0.5m;
            for (int i = 0; i < segmentCount; ++i)
            {
                Segments.Add(new TreadSegment(nextSegmentPosition, tankBody, treadSegmentDescription));

                //The tread offset starts at the front of the vehicle and moves backward.
                nextSegmentPosition.Z += spacing;
            }


            //Don't let the tread segments rotate relative to each other.
            SegmentAngularBindings = new List <NoRotationJoint>();
            for (int i = 1; i < segmentCount; ++i)
            {
                //Create constraints linking the segments together to ensure that the power of one motor is felt by other segments.
                SegmentAngularBindings.Add(new NoRotationJoint(Segments[i - 1].Entity, Segments[i].Entity));
                //Don't let the tread segments collide.
                CollisionRules.AddRule(Segments[i - 1].Entity, Segments[i].Entity, CollisionRule.NoBroadPhase);
            }

            //Note: You can organize this in different ways. For example, you could have one motor which drives one wheel, which
            //in turn drives other wheels through these NoRotationJoints.

            //In such a one-motor model, it may be a good idea for stability to bind all wheels directly to the drive wheel with
            //NoRotationJoints rather than using a chain of one wheel to the next.

            //Per-wheel drive motors are used in this example just because it is slightly more intuitive at a glance.
            //Each segment is no different than the others.
        }
Пример #8
0
        /// <summary>
        /// Finds a supporting entity, the contact location, and the contact normal.
        /// </summary>
        /// <param name="location">Contact point between the wheel and the support.</param>
        /// <param name="normal">Contact normal between the wheel and the support.</param>
        /// <param name="suspensionLength">Length of the suspension at the contact.</param>
        /// <param name="entity">Supporting object.</param>
        /// <param name="material">Material of the wheel.</param>
        /// <returns>Whether or not any support was found.</returns>
        protected internal override bool FindSupport(out Vector3 location, out Vector3 normal, out float suspensionLength, out Entity entity, out Material material)
        {
            suspensionLength = float.MaxValue;
            location         = Toolbox.NoVector;
            entity           = null;
            normal           = Toolbox.NoVector;
            material         = null;

            Collidable testCollider;
            RayHit     rayHit;

            bool hit = false;

            for (int i = 0; i < detector.CollisionInformation.pairs.Count; i++)
            {
                NarrowPhasePair pair = detector.CollisionInformation.pairs[i];
                testCollider = (pair.BroadPhaseOverlap.entryA == detector.CollisionInformation ? pair.BroadPhaseOverlap.entryB : pair.BroadPhaseOverlap.entryA) as Collidable;
                if (testCollider != null)
                {
                    if (CollisionRules.CollisionRuleCalculator(CollisionRules, testCollider.collisionRules) == CollisionRule.Normal &&
                        testCollider.RayCast(new Ray(wheel.suspension.worldAttachmentPoint, wheel.suspension.worldDirection), wheel.suspension.restLength,
                                             out rayHit) &&
                        rayHit.T < suspensionLength)
                    {
                        suspensionLength = rayHit.T;
                        EntityCollidable entityCollisionInfo;
                        if ((entityCollisionInfo = testCollider as EntityCollidable) != null)
                        {
                            entity   = entityCollisionInfo.Entity;
                            material = entityCollisionInfo.Entity.Material;
                        }
                        else
                        {
                            entity = null;
                            var materialOwner = testCollider as IMaterialOwner;
                            if (materialOwner != null)
                            {
                                material = materialOwner.Material;
                            }
                        }
                        location = rayHit.Location;
                        normal   = rayHit.Normal;
                        hit      = true;
                    }
                }
            }
            if (hit)
            {
                if (suspensionLength > 0)
                {
                    normal.Normalize();
                }
                else
                {
                    Vector3.Negate(ref wheel.suspension.worldDirection, out normal);
                }
                return(true);
            }
            return(false);
        }
Пример #9
0
 public static void Initialize()
 {
     WinConditions        = new WinConditionsRule();
     DistanceBonus        = new DistanceBonusRule();
     EndPhase             = new EndPhaseCleanupRule();
     Stress               = new StressRule();
     Strain               = new StrainRule();
     Deplete              = new DepleteRule();
     OffTheBoard          = new OffTheBoardRule();
     Collision            = new CollisionRules();
     Actions              = new ActionsRule();
     AsteroidLanded       = new AsteroidLandedRule();
     AsteroidHit          = new ObstaclesHitRule();
     MineHit              = new MineHitRule();
     AsteroidObstruction  = new AsteroidObstructionRule();
     Initiative           = new InitiativeRule();
     TargetIsLegalForShot = new TargetIsLegalForShotRule();
     Ionization           = new IonizationRule();
     Jam             = new JamRule();
     TargetLocks     = new TargetLocksRule();
     WeaponsDisabled = new WeaponsDisabledRule();
     BullseyeArc     = new BullseyeArcRule();
     Docking         = new DockingRule();
     TractorBeam     = new TractorBeamRule();
     Force           = new ForceRule();
     Charge          = new ChargeRule();
     Destruction     = new DestructionRule();
     Fuse            = new FuseRule();
     Remotes         = new RemotesRule();
     PurpleManeuvers = new PurpleManeuversRule();
 }
        void BuildStick(Vector3 position, int linkCount, out List <Bone> bones, out List <Entity> boneEntities)
        {
            //Set up a bone chain.
            bones        = new List <Bone>();
            boneEntities = new List <Entity>();
            var previousBoneEntity = new Cylinder(position, 1, .2m);
            var previousBone       = new Bone(previousBoneEntity.Position, previousBoneEntity.Orientation, previousBoneEntity.Radius, previousBoneEntity.Height);

            bones.Add(previousBone);
            boneEntities.Add(previousBoneEntity);


            for (int i = 1; i < linkCount; i++)
            {
                var boneEntity = new Cylinder(previousBone.Position + new Vector3(0, 1, 0), 1, .2m);
                var bone       = new Bone(boneEntity.Position, boneEntity.Orientation, boneEntity.Radius, boneEntity.Height);
                bones.Add(bone);
                boneEntities.Add(boneEntity);

                //Make a relationship between the two bones and entities.
                CollisionRules.AddRule(previousBoneEntity, boneEntity, CollisionRule.NoBroadPhase);
                Vector3 anchor = (previousBoneEntity.Position + boneEntity.Position) / 2;
                //var dynamicsBallSocketJoint = new BallSocketJoint(previousBoneEntity, boneEntity, anchor);
                //var dynamicsAngularFriction = new NoRotationJoint(previousBoneEntity, boneEntity);
                //Space.Add(dynamicsBallSocketJoint);
                //Space.Add(dynamicsAngularFriction);
                var ballSocket   = new IKBallSocketJoint(previousBone, bone, anchor);
                var angularJoint = new IKAngularJoint(previousBone, bone);


                previousBone       = bone;
                previousBoneEntity = boneEntity;
            }
        }
Пример #11
0
        public TreadSegment(Vector3 segmentPosition, Entity body, TreadSegmentDescription treadSegmentDescription)
        {
            Entity = new Cylinder(segmentPosition, treadSegmentDescription.Width, treadSegmentDescription.Radius, treadSegmentDescription.Mass);

            Entity.Material.KineticFriction = treadSegmentDescription.Friction;
            Entity.Material.StaticFriction  = treadSegmentDescription.Friction;
            Entity.Orientation = Quaternion.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);

            //Preventing the occasional pointless collision pair can speed things up.
            CollisionRules.AddRule(Entity, body, CollisionRule.NoBroadPhase);

            //Connect the wheel to the body.
            SuspensionAxisJoint   = new PointOnLineJoint(body, Entity, Entity.Position, Vector3.Down, Entity.Position);
            SuspensionLengthLimit = new LinearAxisLimit(body, Entity, Entity.Position, Entity.Position, Vector3.Down, -treadSegmentDescription.SuspensionLength, 0);
            //This linear axis motor will give the suspension its springiness by pushing the wheels outward.
            SuspensionSpring = new LinearAxisMotor(body, Entity, Entity.Position, Entity.Position, Vector3.Down);
            SuspensionSpring.Settings.Mode       = MotorMode.Servomechanism;
            SuspensionSpring.Settings.Servo.Goal = 0;
            SuspensionSpring.Settings.Servo.SpringSettings.Stiffness = treadSegmentDescription.SuspensionStiffness;
            SuspensionSpring.Settings.Servo.SpringSettings.Damping   = treadSegmentDescription.SuspensionDamping;

            SuspensionAngularJoint = new RevoluteAngularJoint(body, Entity, Vector3.Right);
            //Make the joint extremely rigid.  There are going to be extreme conditions when the wheels get up to speed;
            //we don't want the forces involved to torque the wheel off the frame!
            SuspensionAngularJoint.SpringSettings.Damping   *= Entity.Mass * 50;
            SuspensionAngularJoint.SpringSettings.Stiffness *= Entity.Mass * 50;
            //Motorize the wheel.
            Motor = new RevoluteMotor(body, Entity, Vector3.Left);
            Motor.Settings.VelocityMotor.Softness = treadSegmentDescription.MotorSoftness;
            Motor.Settings.MaximumForce           = treadSegmentDescription.MotorMaximumForce;
        }
Пример #12
0
        void AddBackWheel(Vector3 wheelOffset, Entity body)
        {
            var wheel = new Cylinder(body.Position + wheelOffset, .4m, .5m, 5);

            wheel.Material.KineticFriction = 2.5m;
            wheel.Material.StaticFriction  = 3.5m;
            wheel.Orientation = Quaternion.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);

            //Preventing the occasional pointless collision pair can speed things up.
            CollisionRules.AddRule(wheel, body, CollisionRule.NoBroadPhase);

            //Connect the wheel to the body.
            var pointOnLineJoint = new PointOnLineJoint(body, wheel, wheel.Position, Vector3.Down, wheel.Position);
            var suspensionLimit  = new LinearAxisLimit(body, wheel, wheel.Position, wheel.Position, Vector3.Down, -1, 0);
            //This linear axis motor will give the suspension its springiness by pushing the wheels outward.
            var suspensionSpring = new LinearAxisMotor(body, wheel, wheel.Position, wheel.Position, Vector3.Down);

            suspensionSpring.Settings.Mode       = MotorMode.Servomechanism;
            suspensionSpring.Settings.Servo.Goal = 0;
            suspensionSpring.Settings.Servo.SpringSettings.Stiffness = 300;
            suspensionSpring.Settings.Servo.SpringSettings.Damping   = 70;

            var revoluteAngularJoint = new RevoluteAngularJoint(body, wheel, Vector3.Right);

            //Add the wheel and connection to the space.
            Space.Add(wheel);
            Space.Add(pointOnLineJoint);
            Space.Add(suspensionLimit);
            Space.Add(suspensionSpring);
            Space.Add(revoluteAngularJoint);
        }
        /// <summary>
        /// Constructs a simple character controller.
        /// </summary>
        /// <param name="position">Location to initially place the character.</param>
        /// <param name="characterHeight">The height of the character.</param>
        /// <param name="characterWidth">The diameter of the character.</param>
        /// <param name="supportHeight">The distance above the ground that the bottom of the character's body floats.</param>
        /// <param name="mass">Total mass of the character.</param>
        /// <param name="scale">The scale.</param>
        public CharacterController(Vector3 position, float characterHeight, float characterWidth, float supportHeight, float mass, Vector3 scale)
        {
            IsUpdating           = false;
            characterWidth       = characterWidth * scale.X;
            this.characterHeight = characterHeight * scale.Y;
            this.scale           = scale;
            Body = new Capsule(position, characterHeight - characterWidth, characterWidth / 2, mass);
            collisionPairCollectorPositionOffset = new Vector3(0, -characterHeight / 2 - supportHeight, 0);
            collisionPairCollector = new Box(position + collisionPairCollectorPositionOffset, characterWidth, supportHeight * 2, characterWidth, 1);


            collisionPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate; //Prevents collision detection/contact generation from being run.
            collisionPairCollector.IsAffectedByGravity = false;
            CollisionRules.AddRule(collisionPairCollector, Body, CollisionRule.NoBroadPhase);                        //Prevents the creation of any collision pairs between the body and the collector.
            rayOriginOffset    = new Vector3(0, -characterHeight / 2, 0);
            this.supportHeight = supportHeight;

            Body.LocalInertiaTensorInverse = new Matrix3X3();
            collisionPairCollector.LocalInertiaTensorInverse = new Matrix3X3();
            //Make the body slippery.
            //Note that this will not make all collisions have zero friction;
            //the friction coefficient between a pair of objects is based
            //on a blending of the two objects' materials.
            Body.Material.KineticFriction = 0;
            Body.Material.StaticFriction  = 0;
        }
Пример #14
0
        protected void TryToAdd(Collidable a, Collidable b, Material materialA, Material materialB)
        {
            CollisionRule rule;

            if ((rule = CollisionRules.collisionRuleCalculator(a, b)) < CollisionRule.NoNarrowPhasePair)
            {
                //Clamp the rule to the parent's rule.  Always use the more restrictive option.
                //Don't have to test for NoNarrowPhasePair rule on the parent's rule because then the parent wouldn't exist!
                if (rule < CollisionRule)
                {
                    rule = CollisionRule;
                }
                var pair = new CollidablePair(a, b);
                if (!subPairs.ContainsKey(pair))
                {
                    var newPair = NarrowPhaseHelper.GetPairHandler(ref pair, rule);
                    if (newPair != null)
                    {
                        newPair.UpdateMaterialProperties(materialA, materialB);  //Override the materials, if necessary.
                        newPair.Parent = this;
                        subPairs.Add(pair, newPair);
                    }
                }
                containedPairs.Add(pair);
            }
        }
Пример #15
0
        protected BroadPhaseEntry()
        {
            CollisionRules = new CollisionRules();
            collisionRulesUpdatedDelegate = CollisionRulesUpdated;

            hashCode = (int)(base.GetHashCode() * 0xd8163841);
        }
Пример #16
0
 protected internal CollisionRule GetCollisionRule(BroadPhaseEntry entryA, BroadPhaseEntry entryB)
 {
     if (entryA.IsActive || entryB.IsActive)
     {
         return(CollisionRules.collisionRuleCalculator(entryA, entryB));
     }
     return(CollisionRule.NoBroadPhase);
 }
Пример #17
0
 /// <summary>
 /// Creates a detector volume.
 /// </summary>
 /// <param name="triangleMesh">Arbitrary closed triangle mesh representing the volume.</param>
 /// <param name="queryAccelerator">System used to find nearby objects.</param>
 public DetectorVolume(MeshBoundingBoxTreeData triangleMesh, IQueryAccelerator queryAccelerator)
 {
     TriangleMesh     = new TriangleMesh(triangleMesh);
     QueryAccelerator = queryAccelerator;
     collisionRules   = new CollisionRules()
     {
         group = new CollisionGroup()
     };
 }
Пример #18
0
 public override void Disable()
 {
     if ((One as PhysicsEntity).Body == null || (Two as PhysicsEntity).Body == null)
     {
         base.Disable();
         return;
     }
     CollisionRules.RemoveRule(((PhysicsEntity)One).Body.CollisionInformation, ((PhysicsEntity)Two).Body.CollisionInformation);
     CollisionRules.RemoveRule(((PhysicsEntity)Two).Body.CollisionInformation, ((PhysicsEntity)One).Body.CollisionInformation);
     base.Disable();
 }
Пример #19
0
        private Func <BroadPhaseEntry, bool> GetOverlapFilter(ICollisionRulesOwner rulesOwner)
        {
            bool Filter(BroadPhaseEntry e)
            {
                CollisionRule rule = CollisionRules.GetCollisionRule(e, rulesOwner);

                return(rule <= CollisionRule.NoSolver);
            }

            return(Filter);
        }
Пример #20
0
 public bool IgnoreThis(BroadPhaseEntry entry)
 {
     if (entry is EntityCollidable ec && ec.Entity == Entity)
     {
         return(false);
     }
     if (CollisionRules.GetCollisionRule(entity.CollisionInformation, entry) == CollisionRule.NoBroadPhase)
     {
         return(false);
     }
     return(CollisionUtil.ShouldCollide(entry));
 }
Пример #21
0
        // Must be called by subclasses when they are able to construct an Entity.
        protected void SetEntity(Entity entity)
        {
            if (Entity != null)
            {
                _physicsSystem.RemoveObject(Entity);
                Transform.RemovePhysicsEntity();
            }

            Entity                          = entity;
            Entity.Position                 = Transform.Position;
            Entity.Orientation              = Transform.Rotation;
            Entity.IsAffectedByGravity      = IsAffectedByGravity;
            Entity.PositionUpdateMode       = MapUpdateMode(UpdateMode);
            Entity.AngularDamping           = AngularDamping;
            Entity.LinearDamping            = LinearDamping;
            Entity.Material.Bounciness      = Bounciness;
            Entity.Material.StaticFriction  = StaticFriction;
            Entity.Material.KineticFriction = KineticFriction;

            Entity.Tag = this;
            Entity.CollisionInformation.Tag = this;
            Entity.CollisionInformation.CollisionRules.Group = _physicsSystem.GetCollisionGroup(_layer);

            if (EnabledInHierarchy)
            {
                _physicsSystem.AddObject(Entity);
                Transform.SetPhysicsEntity(Entity);
                if (_isTrigger)
                {
                    SetEntityTrigger();
                }
            }

            _parentCollider = GameObject.GetComponentInParent <Collider>();
            if (_parentCollider != null)
            {
                CollisionRules.AddRule(Entity, _parentCollider.Entity, CollisionRule.NoBroadPhase);

                var jointPosition = (Entity.Position + _parentCollider.Entity.Position) / 2;
                _parentJoint = new WeldJoint(_parentCollider.Entity, Entity, jointPosition);
                _parentJoint.BallSocketJoint.SpringSettings.Stiffness = float.MaxValue;
                _parentJoint.BallSocketJoint.SpringSettings.Damping   = float.MaxValue;
                _parentJoint.BallSocketJoint.IsActive = true;

                _parentJoint.NoRotationJoint.SpringSettings.Damping   = float.MaxValue;
                _parentJoint.NoRotationJoint.SpringSettings.Stiffness = float.MaxValue;
                _parentJoint.NoRotationJoint.IsActive = true;
                _parentJoint.IsActive = true;
                _physicsSystem.AddObject(_parentJoint);
                _parentCollider.Transform.PositionManuallyChanged += OnAttachedParentManuallyMoved;
            }
        }
Пример #22
0
        private CollisionRule CustomCollisionRuleCalculator(ICollisionRulesOwner aOwner, ICollisionRulesOwner bOwner)
        {
            CollisionRules a         = aOwner.CollisionRules;
            CollisionRules b         = bOwner.CollisionRules;
            CollisionRule  groupRule = CollisionRules.GetGroupCollisionRuleDefault(a, b);

            if (groupRule == CollisionRule.NoBroadPhase)
            {
                return(groupRule);
            }

            return(CollisionRules.GetCollisionRuleDefault(aOwner, bOwner));
        }
Пример #23
0
 public void IgnoreCollision(Collider collider1, Collider collider2, bool ignore)
 {
     if (ignore)
     {
         CollisionRules.AddRule(collider1.collisionEntity_generic.CollisionInformation, collider2.collisionEntity_generic.CollisionInformation, CollisionRule.NoBroadPhase);
         //collider1.collisionEntity_generic.CollisionInformation.CollisionRules.Group = firstStackGroup;
         //collider2.collisionEntity_generic.CollisionInformation.CollisionRules.Group = secondStackGroup;
     }
     else
     {
         CollisionRules.RemoveRule(collider1.collisionEntity_generic.CollisionInformation, collider2.collisionEntity_generic.CollisionInformation);
         //collider1.collisionEntity_generic.CollisionInformation.CollisionRules.Group = null;
         //collider2.collisionEntity_generic.CollisionInformation.CollisionRules.Group = null;
     }
 }
Пример #24
0
        public void OnCollide(object sender, CollisionEventArgs args)
        {
            if (Stuck)
            {
                return;
            }
            double len = GetVelocity().Length();

            SetPosition(args.Info.Position + (GetVelocity() / len) * 0.05f);
            SetVelocity(Location.Zero);
            Gravity = Location.Zero;
            if (HasHat)
            {
                SolidHat = new ModelEntity("invisbox", TheRegion);
                SolidHat.SetMass(0);
                SolidHat.SetPosition(GetPosition());
                SolidHat.SetOrientation(GetOrientation());
                SolidHat.scale   = new Location(0.6, 1.5, 0.6);
                SolidHat.Visible = false;
                SolidHat.CanSave = false;
                TheRegion.SpawnEntity(SolidHat);
            }
            if (args.Info.HitEnt != null)
            {
                PhysicsEntity pe = (PhysicsEntity)args.Info.HitEnt.Tag;
                if (pe is EntityDamageable)
                {
                    ((EntityDamageable)pe).Damage(Damage + DamageTimesVelocity * (double)len);
                }
                Vector3 loc     = (args.Info.Position - pe.GetPosition()).ToBVector();
                Vector3 impulse = GetVelocity().ToBVector() * DamageTimesVelocity / 1000f;
                pe.Body.ApplyImpulse(ref loc, ref impulse);
                StuckTo = pe;
                if (HasHat)
                {
                    CollisionRules.AddRule(pe.Body, SolidHat.Body, CollisionRule.NoBroadPhase); // TODO: Broadcast this info! Perhaps abuse the joint system?
                }
            }
            TheRegion.SendToAll(new PrimitiveEntityUpdatePacketOut(this));
            if (args.Info.HitEnt != null)
            {
                PhysicsEntity  pe  = (PhysicsEntity)args.Info.HitEnt.Tag;
                JointForceWeld jfw = new JointForceWeld(pe, this);
                TheRegion.AddJoint(jfw);
            }
        }
Пример #25
0
        public Turret(Entity tankBody, Vector3 offset)
        {
            var position = offset + tankBody.Position;

            Body = new Cylinder(position, (Fix64)0.7m, (Fix64)0.8m, 8);
            //Position the center of the arm a bit further forward since it will be laying down.
            position.Z -= 2;
            Barrel      = new Cylinder(position, 3, (Fix64)0.2m, 3);
            //Rotate the arm so that it points straight forward (that is, along {0, 0, -1}).
            Barrel.Orientation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.PiOver2);

            TankToTurretJoint       = new RevoluteJoint(tankBody, Body, Body.Position, Vector3.Up);
            TurretBodyToBarrelJoint = new RevoluteJoint(Body, Barrel, Body.Position + new Vector3(0, 0, (Fix64)(-0.5m)), Vector3.Left);

            //Turn on the control constraints. We'll put them into servo mode, but velocity mode would also work just fine.
            TankToTurretJoint.Motor.IsActive      = true;
            TankToTurretJoint.Motor.Settings.Mode = MotorMode.Servomechanism;
            TankToTurretJoint.Motor.Settings.Servo.BaseCorrectiveSpeed = (Fix64)0.5m;
            TankToTurretJoint.Motor.Settings.MaximumForce = 500;
            TankToTurretJoint.Motor.Basis.SetLocalAxes(Vector3.Up, Vector3.Forward);

            TurretBodyToBarrelJoint.Motor.IsActive      = true;
            TurretBodyToBarrelJoint.Motor.Settings.Mode = MotorMode.Servomechanism;
            TurretBodyToBarrelJoint.Motor.Settings.Servo.BaseCorrectiveSpeed = (Fix64)0.5m;
            //We take special care to limit this motor's force to stop the turret from smashing the tank body.
            TurretBodyToBarrelJoint.Motor.Settings.MaximumForce = 300;
            TurretBodyToBarrelJoint.Motor.Basis.SetLocalAxes(Vector3.Right, Vector3.Forward);

            //Don't let the directly connected objects generate collisions. The arm can still hit the tank body, though.
            CollisionRules.AddRule(Body, tankBody, CollisionRule.NoBroadPhase);
            CollisionRules.AddRule(Barrel, Body, CollisionRule.NoBroadPhase);

            //Don't have a lot of leeway downards. The turret will quickly bump the tank body.
            MinimumPitch = -MathHelper.Pi * (Fix64)0.05m;
            MaximumPitch = MathHelper.Pi * (Fix64)0.4m;

            //Build an ammunition pool.
            shellPool = new Queue <Sphere>(MaximumShellCount);

            for (int i = 0; i < MaximumShellCount; ++i)
            {
                var shell = new Sphere(new Vector3(10000, 0, 0), (Fix64)0.2m, 2);
                shell.PositionUpdateMode = BEPUphysics.PositionUpdating.PositionUpdateMode.Continuous;
                shellPool.Enqueue(shell);
            }
        }
Пример #26
0
    static Rules()
    {
        Game = UnityEngine.GameObject.Find("GameManager").GetComponent <GameManagerScript>();

        WinConditions        = new WinConditionsRule(Game);
        DistanceBonus        = new DistanceBonusRule();
        EndPhase             = new EndPhaseCleanupRule();
        Stress               = new StressRule();
        OffTheBoard          = new OffTheBoardRule(Game);
        Collision            = new CollisionRules();
        FiringRange          = new FiringRangeLimit();
        FiringArc            = new FiringArcRule();
        DuplicatedActions    = new DuplicatedActionsRule();
        AsteroidLanded       = new AsteroidLandedRule();
        AsteroidHit          = new AsteroidHitRule();
        AsteroidObstruction  = new AsteroidObstructionRule();
        Initiative           = new InitiativeRule();
        TargetIsLegalForShot = new TargetIsLegalForShotRule();
    }
Пример #27
0
 static Rules()
 {
     WinConditions        = new WinConditionsRule();
     DistanceBonus        = new DistanceBonusRule();
     EndPhase             = new EndPhaseCleanupRule();
     Stress               = new StressRule();
     OffTheBoard          = new OffTheBoardRule();
     Collision            = new CollisionRules();
     DuplicatedActions    = new DuplicatedActionsRule();
     AsteroidLanded       = new AsteroidLandedRule();
     AsteroidHit          = new AsteroidHitRule();
     MineHit              = new MineHitRule();
     AsteroidObstruction  = new AsteroidObstructionRule();
     Initiative           = new InitiativeRule();
     TargetIsLegalForShot = new TargetIsLegalForShotRule();
     Ionization           = new IonizationRule();
     TargetLocks          = new TargetLocksRule();
     Cloak = new CloakRule();
 }
Пример #28
0
            private void onCollision(EntityCollidable sender, Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair)
            {
                var otherEntity = other as EntityCollidable;

                if (otherEntity != null && FollowPlayer && otherEntity == player.character.CharacterController.Body.CollisionInformation)
                {
                    if (!player.canTakeTextures) // we absorbed textures too fast
                    {
                        FollowPlayer = false;
                        Target       = targetModel.Entity.Position;
                        linearMotor.Settings.Servo.Goal = Target;
                        try
                        {
                            CollisionRules.AddRule(Model.Entity, targetModel.Entity, CollisionRule.NoSolver);
                        }
                        catch { }
                    }
                    else
                    {
                        player.giveTexture(this);
                    }
                }
                else if (otherEntity != null && !FollowPlayer)
                {
                    if (!targetModel.Texture.Wireframe) // we launched textures too fast. turn around and go back to the player.
                    {
                        FollowPlayer = true;
                        try
                        {
                            CollisionRules.AddRule(Model.Entity, player.character.CharacterController.Body, CollisionRule.NoSolver);
                        }
                        catch { }
                        Target = player.character.CharacterController.Body.Position;
                        linearMotor.Settings.Servo.Goal = Target;
                    }
                    else
                    {
                        targetModel.GiveTexture(CarriedTex);
                        player.remove(this);
                    }
                }
            }
Пример #29
0
        public Player()
            : base(null, null, 100)
        {
            character = new CharacterControllerInput(GameManager.Space, RenderingDevice.Camera as CharacterCamera, new Vector3(-1, -16, 5));
            character.CharacterController.Body.Tag = this;
            character.CharacterController.HorizontalMotionConstraint.Speed          = 10;
            character.CharacterController.HorizontalMotionConstraint.CrouchingSpeed = 5;
            PhysicsObject = character.CharacterController.Body;                       // for posterity
            PhysicsObject.CollisionInformation.CollisionRules.Group = dynamicObjects; // also for posterity

            rayCastFilter = RayCastFilter;

            sword = new BaseModel(delegate { return(Program.Game.Loader.SwordModel); }, false, true, new Vector3(0.5f, -15, 4.2f));
            CollisionRules.AddRule(sword.Ent, PhysicsObject, CollisionRule.NoBroadPhase);
            sword.Ent.CollisionInformation.LocalPosition = new Vector3(0, -1, 0);
            sword.Ent.Orientation = Quaternion.CreateFromAxisAngle(Vector3.UnitX, -MathHelper.PiOver2);
            swordgrabber          = new MotorizedGrabSpring();
            swordgrabber.Setup(sword.Ent, sword.ModelPosition - Vector3.UnitX * 0.5f);
            sword.Ent.CollisionInformation.Events.PairTouching += onCollision;
        }
Пример #30
0
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public MPRCastingDemo(DemosGame game)
            : base(game)
        {
            bShape = new BoxShape(1, 0, 1);
            //bShape.CollisionMargin = 0;
            aShape = new ConeShape(1, .4f);
            //aShape.CollisionMargin = 0;
            a = new Entity(aShape);
            b = new Entity(bShape);
            CollisionRules.AddRule(a, b, CollisionRule.NoSolver);
            NarrowPhaseHelper.CollisionManagers.Remove(new TypePair(typeof(ConvexCollidable <BoxShape>), typeof(ConvexCollidable <BoxShape>)));
            Space.Add(a);
            Space.Add(b);
            a.Orientation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.PiOver4);
            b.Orientation = Quaternion.Identity;
            aTransform    = new RigidTransform(new Vector3(-10, -10, -10), a.Orientation);
            bTransform    = new RigidTransform(new Vector3(10, 10, 10), b.Orientation);

            game.Camera.Position = new Vector3(0, 5, 17);
        }