Beispiel #1
0
        public AngleJoint CreateAngleJoint(PhysicsSimulator physicsSimulator, Body body1, Body body2, float softness,
                                           float biasFactor)
        {
            AngleJoint angleJoint = CreateAngleJoint(body1, body2, softness, biasFactor);

            physicsSimulator.Add(angleJoint);
            return(angleJoint);
        }
Beispiel #2
0
        public AngleJoint CreateAngleJoint(Body body1, Body body2, float softness, float biasFactor)
        {
            AngleJoint angleJoint = new AngleJoint(body1, body2);

            angleJoint.Softness   = softness;
            angleJoint.BiasFactor = biasFactor;
            return(angleJoint);
        }
Beispiel #3
0
 public SpringPhysicsObject(World world, PhysicsObject physObA, PhysicsObject physObB, Vector2 relativeJointPosition, float springSoftness, float springBiasFactor)
     : base(world, physObA, physObB, relativeJointPosition)
 {
     springJoint             = JointFactory.CreateAngleJoint(world, physObA.fixture.Body, physObB.fixture.Body);
     springJoint.TargetAngle = 0;
     springJoint.Softness    = springSoftness;
     springJoint.BiasFactor  = springBiasFactor;
 }
Beispiel #4
0
        /// <summary>
        /// Creates an angle joint.
        /// </summary>
        /// <param name="world">The world.</param>
        /// <param name="bodyA">The first body.</param>
        /// <param name="bodyB">The second body.</param>
        public static AngleJoint CreateAngleJoint(World world, Body bodyA, Body bodyB)
        {
            AngleJoint angleJoint = new AngleJoint(bodyA, bodyB);

            world.AddJoint(angleJoint);

            return(angleJoint);
        }
Beispiel #5
0
        private Vector2 _upperLegSize      = new Vector2(3, 0.5f); //x=width, y=height

        public Spider(World world, Vector2 position)
        {
            //Load bodies
            Body circle = BodyFactory.CreateCircle(world, SpiderBodyRadius, 0.1f, position);

            circle.BodyType = BodyType.Dynamic;

            //Left upper leg
            Body leftUpper = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f,
                                                         circle.Position - new Vector2(SpiderBodyRadius, 0) -
                                                         new Vector2(_upperLegSize.X / 2, 0));

            leftUpper.BodyType = BodyType.Dynamic;

            //Left lower leg
            Body leftLower = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f,
                                                         circle.Position - new Vector2(SpiderBodyRadius, 0) -
                                                         new Vector2(_upperLegSize.X, 0) -
                                                         new Vector2(_lowerLegSize.X / 2, 0));

            leftLower.BodyType = BodyType.Dynamic;

            //Right upper leg
            Body rightUpper = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f,
                                                          circle.Position + new Vector2(SpiderBodyRadius, 0) +
                                                          new Vector2(_upperLegSize.X / 2, 0));

            rightUpper.BodyType = BodyType.Dynamic;

            //Right lower leg
            Body rightLower = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f,
                                                          circle.Position + new Vector2(SpiderBodyRadius, 0) +
                                                          new Vector2(_upperLegSize.X, 0) +
                                                          new Vector2(_lowerLegSize.X / 2, 0));

            rightLower.BodyType = BodyType.Dynamic;

            //Create joints
            JointFactory.CreateRevoluteJoint(world, circle, leftUpper, new Vector2(SpiderBodyRadius, 0));

            _leftShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, circle, leftUpper);
            _leftShoulderAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, circle, rightUpper, new Vector2(-SpiderBodyRadius, 0));

            _rightShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, circle, rightUpper);
            _rightShoulderAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, leftUpper, leftLower, new Vector2(_upperLegSize.X / 2, 0));
            _leftKneeAngleJoint            = JointFactory.CreateAngleJoint(world, leftUpper, leftLower);
            _leftKneeAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, rightUpper, rightLower,
                                             -new Vector2(_upperLegSize.X / 2, 0));
            _rightKneeAngleJoint            = JointFactory.CreateAngleJoint(world, rightUpper, rightLower);
            _rightKneeAngleJoint.MaxImpulse = 3;
        }
        public override PhysicsJoint CreateAngleJoint(PhysicsBody bodyA, PhysicsBody bodyB,
                                                      float targetAngle)
        {
            AngleJoint farseerJoint = JointFactory.CreateAngleJoint(world, ((FarseerBody)bodyA).Body,
                                                                    ((FarseerBody)bodyB).Body);

            farseerJoint.TargetAngle = targetAngle;
            return(new FarseerJoint(farseerJoint, bodyA, bodyB));
        }
Beispiel #7
0
        public override Joint createJoint()
        {
            var joint = new AngleJoint(bodyA, bodyB);

            joint.collideConnected = collideConnected;
            joint.maxImpulse       = maxImpulse;
            joint.biasFactor       = biasFactor;
            joint.softness         = softness;
            return(joint);
        }
Beispiel #8
0
        public override Joint CreateJoint()
        {
            var joint = new AngleJoint(BodyA, BodyB);

            joint.CollideConnected = CollideConnected;
            joint.MaxImpulse       = MaxImpulse;
            joint.BiasFactor       = BiasFactor;
            joint.Softness         = Softness;
            return(joint);
        }
Beispiel #9
0
        private void AddChainCommandExecute(object parameter)
        {
            Will.Instance.Purge();
            Will.Instance.RunPauseWilling(false);

            var    startPoint   = new Vector2D(300, 800);
            double angle        = MathHelper.ToRadians(15.0f);
            double boxlength    = 50;
            double spacing      = 2;
            double anchorLength = 30;
            double anchorGap    = (boxlength / 2) + spacing + (anchorLength / 2);

            var chainId = Guid.NewGuid();

            var chain = WillHelper.BuildChain(startPoint, boxlength, 3, 1200, spacing, 600, chainId);

            var point2 = new Vector2D(chain[chain.Count - 1].State.Position.Linear.X + anchorGap, startPoint.Y);
            var end2   = WillHelper.AddCircle(anchorLength / 2, 6, double.PositiveInfinity, new ALVector2D(0, point2), chainId);

            end2.IgnoresGravity = true;

            var joint2 = new HingeJoint(chain[chain.Count - 1], end2, point2, new Lifespan())
            {
                DistanceTolerance = 20
            };
            var joint21 = new AngleJoint(chain[chain.Count - 1], end2, new Lifespan())
            {
                Angle = angle
            };

            var point1 = new Vector2D(chain[0].State.Position.Linear.X - anchorGap, startPoint.Y);
            var end1   = WillHelper.AddCircle(anchorLength / 2, 6, double.PositiveInfinity, new ALVector2D(0, point1), chainId);

            chain.Add(end1);
            chain.Add(end2);

            end1.IgnoresGravity = true;
            var joint1 = new HingeJoint(chain[0], end1, point1, new Lifespan())
            {
                DistanceTolerance = 20
            };
            var joint11 = new AngleJoint(end1, chain[0], new Lifespan())
            {
                Angle = angle
            };

            Will.Instance.AddJoint(joint1); Will.Instance.AddJoint(joint11);
            Will.Instance.AddJoint(joint2); Will.Instance.AddJoint(joint21);

            Representation.Instance.RegisterModel(chainId, chain);

            Will.Instance.RunPauseWilling(true);
        }
Beispiel #10
0
        public JumpySpider(World world, Vector2 position)
        {
            // Body
            _circle          = BodyFactory.CreateCircle(world, SpiderBodyRadius, 0.1f, position);
            _circle.BodyType = BodyType.Dynamic;

            // Left upper leg
            _leftUpper          = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X / 2f, 0f));
            _leftUpper.BodyType = BodyType.Dynamic;

            // Left lower leg
            _leftLower          = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X, 0f) - new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftLower.BodyType = BodyType.Dynamic;

            // Right upper leg
            _rightUpper          = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X / 2f, 0f));
            _rightUpper.BodyType = BodyType.Dynamic;

            // Right lower leg
            _rightLower          = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X, 0f) + new Vector2(_lowerLegSize.X / 2f, 0f));
            _rightLower.BodyType = BodyType.Dynamic;

            //Create joints
            JointFactory.CreateRevoluteJoint(world, _circle, _leftUpper, new Vector2(_upperLegSize.X / 2f, 0f));
            _leftShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _leftUpper);
            _leftShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _circle, _rightUpper, new Vector2(-_upperLegSize.X / 2f, 0f));
            _rightShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _rightUpper);
            _rightShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _leftUpper, _leftLower, new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _leftUpper, _leftLower);
            _leftKneeAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _rightUpper, _rightLower, new Vector2(-_lowerLegSize.X / 2f, 0f));
            _rightKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _rightUpper, _rightLower);
            _rightKneeAngleJoint.MaxImpulse = 3;

            //GFX
            _torso    = new Sprite(ContentWrapper.CircleTexture(SpiderBodyRadius, "Square", ContentWrapper.Grey, ContentWrapper.Gold, ContentWrapper.Black, 1f));
            _upperLeg = new Sprite(ContentWrapper.TextureFromShape(_leftUpper.FixtureList[0].Shape, ContentWrapper.Grey, ContentWrapper.Black));
            _lowerLeg = new Sprite(ContentWrapper.TextureFromShape(_leftLower.FixtureList[0].Shape, ContentWrapper.Gold, ContentWrapper.Black));

            _flexed = false;
            _timer  = 0f;

            _leftShoulderAngleJoint.TargetAngle = ShoulderRelaxed;
            _leftKneeAngleJoint.TargetAngle     = KneeRelaxed;

            _rightShoulderAngleJoint.TargetAngle = -ShoulderRelaxed;
            _rightKneeAngleJoint.TargetAngle     = -KneeRelaxed;
        }
        public override Joint CreateJoint()
        {
            AngleJoint joint = new AngleJoint(BodyA, BodyB)
            {
                CollideConnected = CollideConnected,
                MaxImpulse       = MaxImpulse,
                BiasFactor       = BiasFactor,
                Softness         = Softness
            };

            return(joint);
        }
Beispiel #12
0
        /// <summary>
        /// Connects the figure's body parts
        /// </summary>
        /// <param name="world">The physics world to add the joints to</param>
        private void ConnectBody(World world)
        {
            upright                  = JointFactory.CreateAngleJoint(world, torso, gyro);
            upright.MaxImpulse       = maxImpulse;
            upright.TargetAngle      = 0.0f;
            upright.CollideConnected = false;

            r_neck = JointFactory.CreateRevoluteJoint(world, head, torso, -Vector2.UnitY * 20 * MainGame.PIXEL_TO_METER);
            neck   = JointFactory.CreateAngleJoint(world, head, torso);
            neck.CollideConnected = false;
            neck.MaxImpulse       = maxImpulse;

            r_leftShoulder = JointFactory.CreateRevoluteJoint(world, leftUpperArm, torso, -Vector2.UnitY * 15 * MainGame.PIXEL_TO_METER);
            leftShoulder   = JointFactory.CreateAngleJoint(world, leftUpperArm, torso);
            leftShoulder.CollideConnected = false;
            leftShoulder.MaxImpulse       = maxImpulse;

            r_rightShoulder = JointFactory.CreateRevoluteJoint(world, rightUpperArm, torso, -Vector2.UnitY * 15 * MainGame.PIXEL_TO_METER);
            rightShoulder   = JointFactory.CreateAngleJoint(world, rightUpperArm, torso);
            rightShoulder.CollideConnected = false;
            rightShoulder.MaxImpulse       = maxImpulse;

            r_leftElbow = JointFactory.CreateRevoluteJoint(world, leftLowerArm, leftUpperArm, -Vector2.UnitY * 7.5f * MainGame.PIXEL_TO_METER);
            leftElbow   = JointFactory.CreateAngleJoint(world, leftLowerArm, leftUpperArm);
            leftElbow.CollideConnected = false;
            leftElbow.MaxImpulse       = maxImpulse;

            r_rightElbow = JointFactory.CreateRevoluteJoint(world, rightLowerArm, rightUpperArm, -Vector2.UnitY * 7.5f * MainGame.PIXEL_TO_METER);
            rightElbow   = JointFactory.CreateAngleJoint(world, rightLowerArm, rightUpperArm);
            rightElbow.CollideConnected = false;
            rightElbow.MaxImpulse       = maxImpulse;

            r_leftHip = JointFactory.CreateRevoluteJoint(world, leftUpperLeg, torso, Vector2.UnitY * 15 * MainGame.PIXEL_TO_METER);
            leftHip   = JointFactory.CreateAngleJoint(world, leftUpperLeg, torso);
            leftHip.CollideConnected = false;
            leftHip.MaxImpulse       = maxImpulse;

            r_rightHip = JointFactory.CreateRevoluteJoint(world, rightUpperLeg, torso, Vector2.UnitY * 15 * MainGame.PIXEL_TO_METER);
            rightHip   = JointFactory.CreateAngleJoint(world, rightUpperLeg, torso);
            rightHip.CollideConnected = false;
            rightHip.MaxImpulse       = maxImpulse;

            r_leftKnee = JointFactory.CreateRevoluteJoint(world, leftLowerLeg, leftUpperLeg, -Vector2.UnitY * 7.5f * MainGame.PIXEL_TO_METER);
            leftKnee   = JointFactory.CreateAngleJoint(world, leftUpperLeg, leftLowerLeg);
            leftKnee.CollideConnected = false;
            leftKnee.MaxImpulse       = maxImpulse;

            r_rightKnee = JointFactory.CreateRevoluteJoint(world, rightLowerLeg, rightUpperLeg, -Vector2.UnitY * 7.5f * MainGame.PIXEL_TO_METER);
            rightKnee   = JointFactory.CreateAngleJoint(world, rightUpperLeg, rightLowerLeg);
            rightKnee.CollideConnected = false;
            rightKnee.MaxImpulse       = maxImpulse;
        }
        public JumpySpider(World world, Vector2 position)
        {
            flexTime  = (float)(random.NextDouble() * 5000 + 2000);
            relaxTime = (float)(random.NextDouble() * 5000 + 2000);

            // Body
            _circle          = BodyFactory.CreateCircle(world, SpiderBodyRadius, 0.1f, position);
            _circle.BodyType = BodyType.Dynamic;

            // Left upper leg
            _leftUpper          = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X / 2f, 0f));
            _leftUpper.BodyType = BodyType.Dynamic;

            // Left lower leg
            _leftLower          = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X, 0f) - new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftLower.BodyType = BodyType.Dynamic;

            // Right upper leg
            _rightUpper          = BodyFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X / 2f, 0f));
            _rightUpper.BodyType = BodyType.Dynamic;

            // Right lower leg
            _rightLower          = BodyFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X, 0f) + new Vector2(_lowerLegSize.X / 2f, 0f));
            _rightLower.BodyType = BodyType.Dynamic;

            //Create joints
            JointFactory.CreateRevoluteJoint(world, _circle, _leftUpper, new Vector2(_upperLegSize.X / 2f, 0f));
            _leftShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _leftUpper);
            _leftShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _circle, _rightUpper, new Vector2(-_upperLegSize.X / 2f, 0f));
            _rightShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _rightUpper);
            _rightShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _leftUpper, _leftLower, new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _leftUpper, _leftLower);
            _leftKneeAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _rightUpper, _rightLower, new Vector2(-_lowerLegSize.X / 2f, 0f));
            _rightKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _rightUpper, _rightLower);
            _rightKneeAngleJoint.MaxImpulse = 3;

            _flexed = false;
            _timer  = 0f;

            _leftShoulderAngleJoint.TargetAngle = ShoulderRelaxed;
            _leftKneeAngleJoint.TargetAngle     = KneeRelaxed;

            _rightShoulderAngleJoint.TargetAngle = -ShoulderRelaxed;
            _rightKneeAngleJoint.TargetAngle     = -KneeRelaxed;
        }
Beispiel #14
0
        public static Tuple <HingeJoint, AngleJoint> ConnectWith(this BaseModelBody parentBody, BaseModelBody childBody, Vector2D hingeLocation)
        {
            var hinge = new HingeJoint(parentBody, childBody, hingeLocation, new Lifespan())
            {
                DistanceTolerance = 50,
                Softness          = 10000.1
            };
            var angle = new AngleJoint(parentBody, childBody, new Lifespan())
            {
                Softness = -0.00000001, BiasFactor = 0.3
            };

            return(new Tuple <HingeJoint, AngleJoint>(hinge, angle));
        }
Beispiel #15
0
        internal override void UpdateJoint()
        {
            base.UpdateJoint();
            if (this.joint == null)
            {
                return;
            }

            AngleJoint j = this.joint as AngleJoint;

            j.TargetAngle = this.angle;
            j.BiasFactor  = this.biasFactor;
            j.Softness    = this.softness;
            j.MaxImpulse  = this.maxImpulse < 0.0f ? float.MaxValue : PhysicsConvert.ToPhysicalUnit(this.maxImpulse);
        }
Beispiel #16
0
        public Spider(World world, ScreenManager screenManager, Vector2 position)
        {
            _batch = screenManager.SpriteBatch;

            //Load bodies
            _circle          = world.CreateCircle(SpiderBodyRadius, 0.1f, position);
            _circle.BodyType = BodyType.Dynamic;

            //Left upper leg
            _leftUpper          = world.CreateRectangle(_upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X / 2f, 0f));
            _leftUpper.BodyType = BodyType.Dynamic;

            //Left lower leg
            _leftLower          = world.CreateRectangle(_lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position - new Vector2(SpiderBodyRadius, 0f) - new Vector2(_upperLegSize.X, 0f) - new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftLower.BodyType = BodyType.Dynamic;

            //Right upper leg
            _rightUpper          = world.CreateRectangle(_upperLegSize.X, _upperLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X / 2f, 0f));
            _rightUpper.BodyType = BodyType.Dynamic;

            //Right lower leg
            _rightLower          = world.CreateRectangle(_lowerLegSize.X, _lowerLegSize.Y, 0.1f, _circle.Position + new Vector2(SpiderBodyRadius, 0f) + new Vector2(_upperLegSize.X, 0f) + new Vector2(_lowerLegSize.X / 2f, 0f));
            _rightLower.BodyType = BodyType.Dynamic;

            //Create joints
            JointFactory.CreateRevoluteJoint(world, _circle, _leftUpper, new Vector2(_upperLegSize.X / 2f, 0f));
            _leftShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _leftUpper);
            _leftShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _circle, _rightUpper, new Vector2(-_upperLegSize.X / 2f, 0f));
            _rightShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, _circle, _rightUpper);
            _rightShoulderAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _leftUpper, _leftLower, new Vector2(_lowerLegSize.X / 2f, 0f));
            _leftKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _leftUpper, _leftLower);
            _leftKneeAngleJoint.MaxImpulse = 3f;

            JointFactory.CreateRevoluteJoint(world, _rightUpper, _rightLower, new Vector2(-_lowerLegSize.X / 2f, 0f));
            _rightKneeAngleJoint            = JointFactory.CreateAngleJoint(world, _rightUpper, _rightLower);
            _rightKneeAngleJoint.MaxImpulse = 3;

            //GFX
            AssetCreator creator = screenManager.Assets;

            _torso    = new Sprite(creator.CircleTexture(SpiderBodyRadius, MaterialType.Waves, Color.Gray, 1f, 24f));
            _upperLeg = new Sprite(creator.TextureFromShape(_leftUpper.FixtureList[0].Shape, MaterialType.Blank, Color.DimGray, 1f));
            _lowerLeg = new Sprite(creator.TextureFromShape(_leftLower.FixtureList[0].Shape, MaterialType.Blank, Color.DarkSlateGray, 1f));
        }
Beispiel #17
0
 /// <summary>
 /// Sends the stick figure to its default pose
 /// </summary>
 public void Stand()
 {
     Crouching              = false;
     upright.TargetAngle    = 0.0f;
     walkStage              = 0;
     leftHip.TargetAngle    = 3 * MathHelper.PiOver4;
     leftKnee.TargetAngle   = -5 * MathHelper.PiOver4;
     rightHip.TargetAngle   = -3 * MathHelper.PiOver4;
     rightKnee.TargetAngle  = -3 * MathHelper.PiOver4;
     leftLowerLeg.Friction  = 0f;
     rightLowerLeg.Friction = 0f;
     AngleJoint[] checkThese = new AngleJoint[] { leftHip, leftKnee, rightHip, rightKnee };
     if (JointsAreInPosition(checkThese))
     {
         leftLowerLeg.Friction  = 100f;
         rightLowerLeg.Friction = 100f;
     }
 }
        public InteractiveAngleJoint(float angle1, float angle2, float angle3, float angle4, float angleMin,
                                     float angleMax, float softness, Vector2 anchor, Body body1, Body body2)
        {
            this.angle1   = angle1;
            this.angle2   = angle2;
            this.angle3   = angle3;
            this.angle4   = angle4;
            this.angleMin = angleMin;
            this.angleMax = angleMax;
            this.softness = softness;
            this.body1    = body1;
            this.body2    = body2;
            this.anchor   = anchor;

            revoluteJoint          = new RevoluteJoint(body1, body2, anchor);
            revoluteJoint.Softness = softness;
            angleJoint             = new AngleJoint(body1, body2);
            circularInterpolator   = new CircularInterpolator(angle1, angle2, angle3, angle4, angleMin, angleMax);
        }
Beispiel #19
0
        private void AddCore(Guid geneApplicationId, BaseGeneViewModel gene)
        {
            var core  = (CoreGeneViewModel)gene;
            var model = core.GetModelDuplicate();

            model.Id = geneApplicationId;

            var coreBody = WillHelper.CreateCoreBody(model, geneApplicationId);

            var nodes = WillHelper.BuildNodeSlots(coreBody, geneApplicationId);

            coreBody.Children = nodes;
            var corePos = coreBody.State.Position;

            var joints = new List <Joint>();

            foreach (var node in nodes)
            {
                var hinge = new HingeJoint(coreBody, node, (2 * node.State.Position.Linear + 8 * corePos.Linear) * 0.1f, new Lifespan())
                {
                    DistanceTolerance = 10,
                    Softness          = 100.0
                };
                var angle = new AngleJoint(coreBody, node, new Lifespan())
                {
                    Softness = 0.0001, BiasFactor = 0.2f
                };

                joints.Add(hinge);
                joints.Add(angle);
            }


            Will.Instance.AddModelBodies(new List <BaseModelBody> {
                coreBody
            }.Concat(nodes).ToList());
            Will.Instance.AddJoints(joints);
        }
Beispiel #20
0
        private AngleJointTest()
        {
            World.CreateEdge(new Vector2(-40, 0), new Vector2(40, 0));

            Body fA = World.CreateRectangle(4, 4, 1, new Vector2(-5, 4));

            fA.BodyType = BodyType.Dynamic;

            Body fB = World.CreateRectangle(4, 4, 1, new Vector2(5, 4));

            fB.BodyType = BodyType.Dynamic;

            AngleJoint joint = new AngleJoint(fA, fB);

            joint.TargetAngle = (float)Math.PI / 2;
            World.Add(joint);

            //Keep a body at a fixed angle without a joint
            Body fC = World.CreateRectangle(4, 4, 1, new Vector2(10, 4));

            fC.BodyType      = BodyType.Dynamic;
            fC.Rotation      = (float)(Math.PI / 3);
            fC.FixedRotation = true; // Or set the Inertia to float.MaxValue
        }
        private AngleJointTest()
        {
            BodyFactory.CreateEdge(World, new Vector2(-40, 0), new Vector2(40, 0));

            Body fA = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(-5, 4));

            fA.BodyType = BodyType.Dynamic;

            Body fB = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(5, 4));

            fB.BodyType = BodyType.Dynamic;

            AngleJoint joint = new AngleJoint(fA, fB);

            joint.TargetAngle = MathConstants.Pi / 2;
            World.AddJoint(joint);

            //Keep a body at a fixed angle without a joint
            Body fC = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(10, 4));

            fC.BodyType      = BodyType.Dynamic;
            fC.Rotation      = MathConstants.Pi / 3;
            fC.FixedRotation = true; // Or set the Inertia to float.MaxValue
        }
Beispiel #22
0
        private SerializationTest()
        {
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-20, 0), new Vector2(20, 0));

            //Friction and distance joint
            {
                Body bodyA = BodyFactory.CreateCircle(World, 1, 1.5f, new Vector2(10, 25));
                bodyA.BodyType = BodyType.Dynamic;

                Body bodyB = BodyFactory.CreateRectangle(World, 1, 1, 1, new Vector2(-1, 25));
                bodyB.BodyType = BodyType.Dynamic;

                FrictionJoint frictionJoint = JointFactory.CreateFrictionJoint(World, bodyB, ground, Vector2.Zero);
                frictionJoint.CollideConnected = true;
                frictionJoint.MaxForce         = 100;

                JointFactory.CreateDistanceJoint(World, bodyA, bodyB);
            }

            //Wheel joint
            {
                Vertices vertices = new Vertices(6);
                vertices.Add(new Vector2(-1.5f, -0.5f));
                vertices.Add(new Vector2(1.5f, -0.5f));
                vertices.Add(new Vector2(1.5f, 0.0f));
                vertices.Add(new Vector2(0.0f, 0.9f));
                vertices.Add(new Vector2(-1.15f, 0.9f));
                vertices.Add(new Vector2(-1.5f, 0.2f));

                Body carBody = BodyFactory.CreatePolygon(World, vertices, 1, new Vector2(0, 1));
                carBody.BodyType = BodyType.Dynamic;

                Body wheel1 = BodyFactory.CreateCircle(World, 0.4f, 1, new Vector2(-1.0f, 0.35f));
                wheel1.BodyType = BodyType.Dynamic;
                wheel1.Friction = 0.9f;

                Body wheel2 = BodyFactory.CreateCircle(World, 0.4f, 1, new Vector2(1.0f, 0.4f));
                wheel2.BodyType = BodyType.Dynamic;
                wheel2.Friction = 0.9f;

                Vector2 axis = new Vector2(0.0f, 1.0f);

                WheelJoint spring1 = JointFactory.CreateWheelJoint(World, carBody, wheel1, axis);
                spring1.MotorSpeed     = 0.0f;
                spring1.MaxMotorTorque = 20.0f;
                spring1.MotorEnabled   = true;
                spring1.Frequency      = 4;
                spring1.DampingRatio   = 0.7f;

                WheelJoint spring2 = JointFactory.CreateWheelJoint(World, carBody, wheel2, axis);
                spring2.MotorSpeed     = 0.0f;
                spring2.MaxMotorTorque = 10.0f;
                spring2.MotorEnabled   = false;
                spring2.Frequency      = 4;
                spring2.DampingRatio   = 0.7f;
            }

            //Prismatic joint
            {
                Body body = BodyFactory.CreateRectangle(World, 2, 2, 5, new Vector2(-10.0f, 10.0f));
                body.BodyType = BodyType.Dynamic;
                body.Rotation = 0.5f * Settings.Pi;

                Vector2 axis = new Vector2(2.0f, 1.0f);
                axis.Normalize();

                PrismaticJoint joint = JointFactory.CreatePrismaticJoint(World, ground, body, Vector2.Zero, axis);
                joint.MotorSpeed    = 5.0f;
                joint.MaxMotorForce = 1000.0f;
                joint.MotorEnabled  = true;
                joint.LowerLimit    = -10.0f;
                joint.UpperLimit    = 20.0f;
                joint.LimitEnabled  = true;
            }

            // Pulley joint
            {
                Body body1 = BodyFactory.CreateRectangle(World, 2, 4, 5, new Vector2(-10.0f, 16.0f));
                body1.BodyType = BodyType.Dynamic;

                Body body2 = BodyFactory.CreateRectangle(World, 2, 4, 5, new Vector2(10.0f, 16.0f));
                body2.BodyType = BodyType.Dynamic;

                Vector2 anchor1      = new Vector2(-10.0f, 16.0f + 2.0f);
                Vector2 anchor2      = new Vector2(10.0f, 16.0f + 2.0f);
                Vector2 worldAnchor1 = new Vector2(-10.0f, 16.0f + 2.0f + 12.0f);
                Vector2 worldAnchor2 = new Vector2(10.0f, 16.0f + 2.0f + 12.0f);

                JointFactory.CreatePulleyJoint(World, body1, body2, anchor1, anchor2, worldAnchor1, worldAnchor2, 1.5f, true);
            }

            //Revolute joint
            {
                Body ball = BodyFactory.CreateCircle(World, 3.0f, 5.0f, new Vector2(5.0f, 30.0f));
                ball.BodyType = BodyType.Dynamic;

                Body polygonBody = BodyFactory.CreateRectangle(World, 20, 0.4f, 2, new Vector2(10, 10));
                polygonBody.BodyType = BodyType.Dynamic;
                polygonBody.IsBullet = true;

                RevoluteJoint joint = JointFactory.CreateRevoluteJoint(World, ground, polygonBody, new Vector2(10, 0));
                joint.LowerLimit   = -0.25f * Settings.Pi;
                joint.UpperLimit   = 0.0f * Settings.Pi;
                joint.LimitEnabled = true;
            }

            //Weld joint
            {
                PolygonShape shape = new PolygonShape(PolygonUtils.CreateRectangle(0.5f, 0.125f), 20);

                Body prevBody = ground;
                for (int i = 0; i < 10; ++i)
                {
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = new Vector2(-14.5f + 1.0f * i, 5.0f);
                    body.CreateFixture(shape);

                    Vector2 anchor = new Vector2(0.5f, 0);

                    if (i == 0)
                    {
                        anchor = new Vector2(-15f, 5);
                    }

                    JointFactory.CreateWeldJoint(World, prevBody, body, anchor, new Vector2(-0.5f, 0));
                    prevBody = body;
                }
            }

            //Rope joint
            {
                LinkFactory.CreateChain(World, new Vector2(-10, 10), new Vector2(-20, 10), 0.1f, 0.5f, 10, 0.1f, true);
            }

            //Angle joint
            {
                Body fA = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(-5, 4));
                fA.BodyType = BodyType.Dynamic;
                fA.Rotation = (float)(Math.PI / 3);

                Body fB = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(5, 4));
                fB.BodyType = BodyType.Dynamic;

                AngleJoint joint = new AngleJoint(fA, fB);
                joint.TargetAngle = (float)Math.PI / 2;
                World.AddJoint(joint);
            }

            //Motor joint
            {
                Body body = BodyFactory.CreateRectangle(World, 4, 1, 2, new Vector2(0, 35));
                body.BodyType = BodyType.Dynamic;
                body.Friction = 0.6f;

                MotorJoint motorJoint = JointFactory.CreateMotorJoint(World, ground, body);
                motorJoint.MaxForce      = 1000.0f;
                motorJoint.MaxTorque     = 1000.0f;
                motorJoint.LinearOffset  = new Vector2(0, 35);
                motorJoint.AngularOffset = (float)(Math.PI / 3f);
            }
        }
Beispiel #23
0
        private void AddSlot(BaseGeneViewModel gene)
        {
            Will.Instance.RunPauseWilling(false);

            var slotGene = (NodeGeneViewModel)gene;

            var boneBody = Will.Instance.Bodies.RandomOrDefault <BoneBody>(b => b.Model.ChildSlots.Any(s => s.IsOccupied == false));

            if (boneBody == null)
            {
                Will.Instance.RunPauseWilling(true);
                return;
            }

            var parPos = boneBody.State.Position;

            var randSlot = boneBody.Model.ChildSlots.Where(s => s.IsOccupied == false).RandomOrDefault();

            var slot = slotGene.GetModelDuplicate();

            slot.Direction          = randSlot.Direction;
            slot.DistanceFromCenter = randSlot.DistanceFromCenter;
            slot.Orientation        = randSlot.Orientation;

            randSlot.IsOccupied = true;

            var slotBody = WillHelper.CreateConnectionSlotBody(slot, boneBody.ModelId);


            var slotXAngle = slot.Direction + parPos.Angular;
            var slotCenter = Vector2D.Rotate(slotXAngle, new Vector2D(slot.DistanceFromCenter, 0.0f));
            var slotPos    = new ALVector2D(slot.Orientation + slotXAngle, slotCenter + parPos.Linear);

            slotBody.State.Position = slotPos;
            slotBody.ApplyPosition();

            slotBody.Parent = boneBody;

            boneBody.Children.Add(slotBody);

            var joints = new List <Joint>();

            var nodePos = slotBody.State.Position;

            var hinge = new HingeJoint(boneBody, slotBody, (slot.Size * nodePos.Linear + boneBody.Model.Length * parPos.Linear) * (1 / (slot.Size + boneBody.Model.Length)), new Lifespan())
            {
                DistanceTolerance = 50,
                Softness          = 10.1
            };
            var angle = new AngleJoint(boneBody, slotBody, new Lifespan())
            {
                Softness = 0.00001
            };

            joints.Add(hinge);
            joints.Add(angle);

            Will.Instance.AddBody(slotBody);
            Will.Instance.AddJoints(joints);

            Will.Instance.RunPauseWilling(true);
        }
Beispiel #24
0
        public void Load(Demo demo, PhysicsSimulator physicsSimulator)
        {
            //Load bodies
            _spiderBody          = BodyFactory.Instance.CreateCircleBody(physicsSimulator, _spiderBodyRadius, 1);
            _spiderBody.Position = _position;
            _spiderBody.IsStatic = false;
            demo.AddCircleToCanvas(_spiderBody, _spiderBodyRadius);
            _leftUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X,
                                                                         _upperLegSize.Y,
                                                                         1);
            _leftUpperLegBody.Position = _spiderBody.Position - new Vector2(_spiderBodyRadius, 0) -
                                         new Vector2(_upperLegSize.X / 2, 0);
            demo.AddRectangleToCanvas(_leftUpperLegBody, Colors.White, new Vector2(_upperLegSize.X, _upperLegSize.Y));

            _leftLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X,
                                                                         _lowerLegSize.Y,
                                                                         1);
            _leftLowerLegBody.Position = _spiderBody.Position - new Vector2(_spiderBodyRadius, 0) -
                                         new Vector2(_upperLegSize.X, 0) - new Vector2(_lowerLegSize.X / 2, 0);
            demo.AddRectangleToCanvas(_leftLowerLegBody, Colors.Red, new Vector2(_lowerLegSize.X, _lowerLegSize.Y));

            _rightUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X,
                                                                          _upperLegSize.Y, 1);
            _rightUpperLegBody.Position = _spiderBody.Position + new Vector2(_spiderBodyRadius, 0) +
                                          new Vector2(_upperLegSize.X / 2, 0);
            demo.AddRectangleToCanvas(_rightUpperLegBody, Colors.White, new Vector2(_upperLegSize.X, _upperLegSize.Y));

            _rightLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X,
                                                                          _lowerLegSize.Y, 1);
            _rightLowerLegBody.Position = _spiderBody.Position + new Vector2(_spiderBodyRadius, 0) +
                                          new Vector2(_upperLegSize.X, 0) + new Vector2(_lowerLegSize.X / 2, 0);
            demo.AddRectangleToCanvas(_rightLowerLegBody, Colors.Red, new Vector2(_lowerLegSize.X, _lowerLegSize.Y));

            //load geometries
            _spiderGeom       = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, _spiderBody, _spiderBodyRadius, 14);
            _leftUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftUpperLegBody,
                                                                         _upperLegSize.X, _upperLegSize.Y);
            _leftLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftLowerLegBody,
                                                                         _lowerLegSize.X, _lowerLegSize.Y);
            _rightUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightUpperLegBody,
                                                                          _upperLegSize.X, _upperLegSize.Y);
            _rightLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightLowerLegBody,
                                                                          _lowerLegSize.X, _lowerLegSize.Y);
            _spiderGeom.CollisionGroup        = _collisionGroup;
            _leftUpperLegGeom.CollisionGroup  = _collisionGroup;
            _leftLowerLegGeom.CollisionGroup  = _collisionGroup;
            _rightUpperLegGeom.CollisionGroup = _collisionGroup;
            _rightLowerLegGeom.CollisionGroup = _collisionGroup;

            //load joints
            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody,
                                                      _leftUpperLegBody,
                                                      _spiderBody.Position -
                                                      new Vector2(_spiderBodyRadius, 0));
            _leftShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody,
                                                                             _leftUpperLegBody);
            _leftShoulderAngleJoint.TargetAngle = -.4f;
            _leftShoulderAngleJoint.MaxImpulse  = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody,
                                                      _rightUpperLegBody,
                                                      _spiderBody.Position +
                                                      new Vector2(_spiderBodyRadius, 0));
            _rightShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody,
                                                                              _rightUpperLegBody);
            _rightShoulderAngleJoint.TargetAngle = .4f;
            _leftShoulderAngleJoint.MaxImpulse   = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _leftUpperLegBody,
                                                      _leftLowerLegBody,
                                                      _spiderBody.Position -
                                                      new Vector2(_spiderBodyRadius, 0) -
                                                      new Vector2(_upperLegSize.X, 0));
            _leftKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _leftUpperLegBody,
                                                                         _leftLowerLegBody);
            _leftKneeAngleJoint.TargetAngle = -_kneeTargetAngle;
            _leftKneeAngleJoint.MaxImpulse  = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _rightUpperLegBody,
                                                      _rightLowerLegBody,
                                                      _spiderBody.Position +
                                                      new Vector2(_spiderBodyRadius, 0) +
                                                      new Vector2(_upperLegSize.X, 0));
            _rightKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _rightUpperLegBody,
                                                                          _rightLowerLegBody);
            _rightKneeAngleJoint.TargetAngle = _kneeTargetAngle;
            _rightKneeAngleJoint.MaxImpulse  = 300;
        }
Beispiel #25
0
        public void Load(GraphicsDevice graphicsDevice, PhysicsSimulator physicsSimulator)
        {
            _spiderTexture = DrawingHelper.CreateCircleTexture(graphicsDevice, spiderBodyRadius, Color.White,
                                                               Color.Black);
            _spiderOrigin = new Vector2(_spiderTexture.Width / 2f, _spiderTexture.Height / 2f);

            _upperLegTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, (int)_upperLegSize.X,
                                                                    (int)_upperLegSize.Y, Color.White, Color.Black);
            _upperLegOrigin = new Vector2(_upperLegTexture.Width / 2f, _upperLegTexture.Height / 2f);

            _lowerLegTexture = DrawingHelper.CreateRectangleTexture(graphicsDevice, (int)_lowerLegSize.X,
                                                                    (int)_lowerLegSize.Y, Color.Red, Color.Black);
            _lowerLegOrigin = new Vector2(_lowerLegTexture.Width / 2f, _lowerLegTexture.Height / 2f);

            //Load bodies
            _spiderBody          = BodyFactory.Instance.CreateCircleBody(physicsSimulator, spiderBodyRadius, 1);
            _spiderBody.Position = _position;
            _spiderBody.IsStatic = false;

            _leftUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X,
                                                                         _upperLegSize.Y,
                                                                         1);
            _leftUpperLegBody.Position = _spiderBody.Position - new Vector2(spiderBodyRadius, 0) -
                                         new Vector2(_upperLegSize.X / 2, 0);

            _leftLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X,
                                                                         _lowerLegSize.Y,
                                                                         1);
            _leftLowerLegBody.Position = _spiderBody.Position - new Vector2(spiderBodyRadius, 0) -
                                         new Vector2(_upperLegSize.X, 0) - new Vector2(_lowerLegSize.X / 2, 0);

            _rightUpperLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _upperLegSize.X,
                                                                          _upperLegSize.Y, 1);
            _rightUpperLegBody.Position = _spiderBody.Position + new Vector2(spiderBodyRadius, 0) +
                                          new Vector2(_upperLegSize.X / 2, 0);

            _rightLowerLegBody = BodyFactory.Instance.CreateRectangleBody(physicsSimulator, _lowerLegSize.X,
                                                                          _lowerLegSize.Y, 1);
            _rightLowerLegBody.Position = _spiderBody.Position + new Vector2(spiderBodyRadius, 0) +
                                          new Vector2(_upperLegSize.X, 0) + new Vector2(_lowerLegSize.X / 2, 0);

            //load geometries
            _spiderGeom       = GeomFactory.Instance.CreateCircleGeom(physicsSimulator, _spiderBody, spiderBodyRadius, 14);
            _leftUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftUpperLegBody,
                                                                         _upperLegSize.X, _upperLegSize.Y);
            _leftLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _leftLowerLegBody,
                                                                         _lowerLegSize.X, _lowerLegSize.Y);
            _rightUpperLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightUpperLegBody,
                                                                          _upperLegSize.X, _upperLegSize.Y);
            _rightLowerLegGeom = GeomFactory.Instance.CreateRectangleGeom(physicsSimulator, _rightLowerLegBody,
                                                                          _lowerLegSize.X, _lowerLegSize.Y);
            _spiderGeom.CollisionGroup        = _collisionGroup;
            _leftUpperLegGeom.CollisionGroup  = _collisionGroup;
            _leftLowerLegGeom.CollisionGroup  = _collisionGroup;
            _rightUpperLegGeom.CollisionGroup = _collisionGroup;
            _rightLowerLegGeom.CollisionGroup = _collisionGroup;

            //load joints
            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody,
                                                      _leftUpperLegBody,
                                                      _spiderBody.Position -
                                                      new Vector2(spiderBodyRadius, 0));
            _leftShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody,
                                                                             _leftUpperLegBody);
            _leftShoulderAngleJoint.TargetAngle = -.4f;
            _leftShoulderAngleJoint.MaxImpulse  = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _spiderBody,
                                                      _rightUpperLegBody,
                                                      _spiderBody.Position +
                                                      new Vector2(spiderBodyRadius, 0));
            _rightShoulderAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _spiderBody,
                                                                              _rightUpperLegBody);
            _rightShoulderAngleJoint.TargetAngle = .4f;
            _leftShoulderAngleJoint.MaxImpulse   = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _leftUpperLegBody,
                                                      _leftLowerLegBody,
                                                      _spiderBody.Position -
                                                      new Vector2(spiderBodyRadius, 0) -
                                                      new Vector2(_upperLegSize.X, 0));
            _leftKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _leftUpperLegBody,
                                                                         _leftLowerLegBody);
            _leftKneeAngleJoint.TargetAngle = -_kneeTargetAngle;
            _leftKneeAngleJoint.MaxImpulse  = 300;

            JointFactory.Instance.CreateRevoluteJoint(physicsSimulator, _rightUpperLegBody,
                                                      _rightLowerLegBody,
                                                      _spiderBody.Position +
                                                      new Vector2(spiderBodyRadius, 0) +
                                                      new Vector2(_upperLegSize.X, 0));
            _rightKneeAngleJoint = JointFactory.Instance.CreateAngleJoint(physicsSimulator, _rightUpperLegBody,
                                                                          _rightLowerLegBody);
            _rightKneeAngleJoint.TargetAngle = _kneeTargetAngle;
            _rightKneeAngleJoint.MaxImpulse  = 300;
        }
Beispiel #26
0
        public AngleJoint CreateAngleJoint(Body body1, Body body2)
        {
            AngleJoint angleJoint = new AngleJoint(body1, body2);

            return(angleJoint);
        }
Beispiel #27
0
        private static void Deserialize(World world, Stream stream)
        {
            List <Body>    bodies   = new List <Body>();
            List <Fixture> fixtures = new List <Fixture>();
            List <Joint>   joints   = new List <Joint>();
            List <Shape>   shapes   = new List <Shape>();

            XMLFragmentElement root = XMLFragmentParser.LoadFromStream(stream);

            if (root.Name.ToLower() != "world")
            {
                throw new Exception();
            }

            //Read gravity
            foreach (XMLFragmentElement element in root.Elements)
            {
                if (element.Name.ToLower() == "gravity")
                {
                    world.Gravity = ReadVector(element);
                    break;
                }
            }

            //Read shapes
            foreach (XMLFragmentElement shapeElement in root.Elements)
            {
                if (shapeElement.Name.ToLower() == "shapes")
                {
                    foreach (XMLFragmentElement element in shapeElement.Elements)
                    {
                        if (element.Name.ToLower() != "shape")
                        {
                            throw new Exception();
                        }

                        ShapeType type    = (ShapeType)Enum.Parse(typeof(ShapeType), element.Attributes[0].Value, true);
                        float     density = float.Parse(element.Attributes[1].Value);

                        switch (type)
                        {
                        case ShapeType.Circle:
                        {
                            CircleShape shape = new CircleShape();
                            shape._density = density;

                            foreach (XMLFragmentElement sn in element.Elements)
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "radius":
                                    shape.Radius = float.Parse(sn.Value);
                                    break;

                                case "position":
                                    shape.Position = ReadVector(sn);
                                    break;

                                default:
                                    throw new Exception();
                                }
                            }

                            shapes.Add(shape);
                        }
                        break;

                        case ShapeType.Polygon:
                        {
                            PolygonShape shape = new PolygonShape();
                            shape._density = density;

                            foreach (XMLFragmentElement sn in element.Elements)
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "vertices":
                                {
                                    List <Vector2> verts = new List <Vector2>(sn.Elements.Count);

                                    foreach (XMLFragmentElement vert in sn.Elements)
                                    {
                                        verts.Add(ReadVector(vert));
                                    }

                                    shape.Vertices = new Vertices(verts);
                                }
                                break;

                                case "centroid":
                                    shape.MassData.Centroid = ReadVector(sn);
                                    break;
                                }
                            }

                            shapes.Add(shape);
                        }
                        break;

                        case ShapeType.Edge:
                        {
                            EdgeShape shape = new EdgeShape();
                            shape._density = density;

                            foreach (XMLFragmentElement sn in element.Elements)
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "hasvertex0":
                                    shape.HasVertex0 = bool.Parse(sn.Value);
                                    break;

                                case "hasvertex3":
                                    shape.HasVertex0 = bool.Parse(sn.Value);
                                    break;

                                case "vertex0":
                                    shape.Vertex0 = ReadVector(sn);
                                    break;

                                case "vertex1":
                                    shape.Vertex1 = ReadVector(sn);
                                    break;

                                case "vertex2":
                                    shape.Vertex2 = ReadVector(sn);
                                    break;

                                case "vertex3":
                                    shape.Vertex3 = ReadVector(sn);
                                    break;

                                default:
                                    throw new Exception();
                                }
                            }
                            shapes.Add(shape);
                        }
                        break;

                        case ShapeType.Chain:
                        {
                            ChainShape shape = new ChainShape();
                            shape._density = density;

                            foreach (XMLFragmentElement sn in element.Elements)
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "vertices":
                                {
                                    List <Vector2> verts = new List <Vector2>(sn.Elements.Count);

                                    foreach (XMLFragmentElement vert in sn.Elements)
                                    {
                                        verts.Add(ReadVector(vert));
                                    }

                                    shape.Vertices = new Vertices(verts);
                                }
                                break;

                                case "nextvertex":
                                    shape.NextVertex = ReadVector(sn);
                                    break;

                                case "prevvertex":
                                    shape.PrevVertex = ReadVector(sn);
                                    break;

                                default:
                                    throw new Exception();
                                }
                            }
                            shapes.Add(shape);
                        }
                        break;
                        }
                    }
                }
            }

            //Read fixtures
            foreach (XMLFragmentElement fixtureElement in root.Elements)
            {
                if (fixtureElement.Name.ToLower() == "fixtures")
                {
                    foreach (XMLFragmentElement element in fixtureElement.Elements)
                    {
                        Fixture fixture = new Fixture();

                        if (element.Name.ToLower() != "fixture")
                        {
                            throw new Exception();
                        }

                        fixture.FixtureId = int.Parse(element.Attributes[0].Value);

                        foreach (XMLFragmentElement sn in element.Elements)
                        {
                            switch (sn.Name.ToLower())
                            {
                            case "filterdata":
                                foreach (XMLFragmentElement ssn in sn.Elements)
                                {
                                    switch (ssn.Name.ToLower())
                                    {
                                    case "categorybits":
                                        fixture._collisionCategories = (Category)int.Parse(ssn.Value);
                                        break;

                                    case "maskbits":
                                        fixture._collidesWith = (Category)int.Parse(ssn.Value);
                                        break;

                                    case "groupindex":
                                        fixture._collisionGroup = short.Parse(ssn.Value);
                                        break;

                                    case "CollisionIgnores":
                                        string[] split = ssn.Value.Split('|');
                                        foreach (string s in split)
                                        {
                                            fixture._collisionIgnores.Add(int.Parse(s));
                                        }
                                        break;
                                    }
                                }

                                break;

                            case "friction":
                                fixture.Friction = float.Parse(sn.Value);
                                break;

                            case "issensor":
                                fixture.IsSensor = bool.Parse(sn.Value);
                                break;

                            case "restitution":
                                fixture.Restitution = float.Parse(sn.Value);
                                break;

                            case "userdata":
                                fixture.UserData = ReadSimpleType(sn, null, false);
                                break;
                            }
                        }

                        fixtures.Add(fixture);
                    }
                }
            }

            //Read bodies
            foreach (XMLFragmentElement bodyElement in root.Elements)
            {
                if (bodyElement.Name.ToLower() == "bodies")
                {
                    foreach (XMLFragmentElement element in bodyElement.Elements)
                    {
                        Body body = new Body(world);

                        if (element.Name.ToLower() != "body")
                        {
                            throw new Exception();
                        }

                        body.BodyType = (BodyType)Enum.Parse(typeof(BodyType), element.Attributes[0].Value, true);

                        foreach (XMLFragmentElement sn in element.Elements)
                        {
                            switch (sn.Name.ToLower())
                            {
                            case "active":
                                bool enabled = bool.Parse(sn.Value);
                                if (enabled)
                                {
                                    body._flags |= BodyFlags.Enabled;
                                }
                                else
                                {
                                    body._flags &= ~BodyFlags.Enabled;
                                }
                                break;

                            case "allowsleep":
                                body.SleepingAllowed = bool.Parse(sn.Value);
                                break;

                            case "angle":
                            {
                                Vector2 position = body.Position;
                                body.SetTransformIgnoreContacts(ref position, float.Parse(sn.Value));
                            }
                            break;

                            case "angulardamping":
                                body.AngularDamping = float.Parse(sn.Value);
                                break;

                            case "angularvelocity":
                                body.AngularVelocity = float.Parse(sn.Value);
                                break;

                            case "awake":
                                body.Awake = bool.Parse(sn.Value);
                                break;

                            case "bullet":
                                body.IsBullet = bool.Parse(sn.Value);
                                break;

                            case "fixedrotation":
                                body.FixedRotation = bool.Parse(sn.Value);
                                break;

                            case "lineardamping":
                                body.LinearDamping = float.Parse(sn.Value);
                                break;

                            case "linearvelocity":
                                body.LinearVelocity = ReadVector(sn);
                                break;

                            case "position":
                            {
                                float   rotation = body.Rotation;
                                Vector2 position = ReadVector(sn);
                                body.SetTransformIgnoreContacts(ref position, rotation);
                            }
                            break;

                            case "userdata":
                                body.UserData = ReadSimpleType(sn, null, false);
                                break;

                            case "bindings":
                            {
                                foreach (XMLFragmentElement pair in sn.Elements)
                                {
                                    Fixture fix = fixtures[int.Parse(pair.Attributes[0].Value)];
                                    fix.Shape = shapes[int.Parse(pair.Attributes[1].Value)].Clone();
                                    fix.CloneOnto(body);
                                }
                                break;
                            }
                            }
                        }

                        bodies.Add(body);
                    }
                }
            }

            //Read joints
            foreach (XMLFragmentElement jointElement in root.Elements)
            {
                if (jointElement.Name.ToLower() == "joints")
                {
                    foreach (XMLFragmentElement n in jointElement.Elements)
                    {
                        Joint joint;

                        if (n.Name.ToLower() != "joint")
                        {
                            throw new Exception();
                        }

                        JointType type = (JointType)Enum.Parse(typeof(JointType), n.Attributes[0].Value, true);

                        int    bodyAIndex = -1, bodyBIndex = -1;
                        bool   collideConnected = false;
                        object userData         = null;

                        foreach (XMLFragmentElement sn in n.Elements)
                        {
                            switch (sn.Name.ToLower())
                            {
                            case "bodya":
                                bodyAIndex = int.Parse(sn.Value);
                                break;

                            case "bodyb":
                                bodyBIndex = int.Parse(sn.Value);
                                break;

                            case "collideconnected":
                                collideConnected = bool.Parse(sn.Value);
                                break;

                            case "userdata":
                                userData = ReadSimpleType(sn, null, false);
                                break;
                            }
                        }

                        Body bodyA = bodies[bodyAIndex];
                        Body bodyB = bodies[bodyBIndex];

                        switch (type)
                        {
                        //case JointType.FixedMouse:
                        //    joint = new FixedMouseJoint();
                        //    break;
                        //case JointType.FixedRevolute:
                        //    break;
                        //case JointType.FixedDistance:
                        //    break;
                        //case JointType.FixedLine:
                        //    break;
                        //case JointType.FixedPrismatic:
                        //    break;
                        //case JointType.FixedAngle:
                        //    break;
                        //case JointType.FixedFriction:
                        //    break;
                        case JointType.Distance:
                            joint = new DistanceJoint();
                            break;

                        case JointType.Friction:
                            joint = new FrictionJoint();
                            break;

                        case JointType.Wheel:
                            joint = new WheelJoint();
                            break;

                        case JointType.Prismatic:
                            joint = new PrismaticJoint();
                            break;

                        case JointType.Pulley:
                            joint = new PulleyJoint();
                            break;

                        case JointType.Revolute:
                            joint = new RevoluteJoint();
                            break;

                        case JointType.Weld:
                            joint = new WeldJoint();
                            break;

                        case JointType.Rope:
                            joint = new RopeJoint();
                            break;

                        case JointType.Angle:
                            joint = new AngleJoint();
                            break;

                        case JointType.Motor:
                            joint = new MotorJoint();
                            break;

                        case JointType.Gear:
                            throw new Exception("GearJoint is not supported.");

                        default:
                            throw new Exception("Invalid or unsupported joint.");
                        }

                        joint.CollideConnected = collideConnected;
                        joint.UserData         = userData;
                        joint.BodyA            = bodyA;
                        joint.BodyB            = bodyB;
                        joints.Add(joint);
                        world.AddJoint(joint);

                        foreach (XMLFragmentElement sn in n.Elements)
                        {
                            // check for specific nodes
                            switch (type)
                            {
                            case JointType.Distance:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "dampingratio":
                                    ((DistanceJoint)joint).DampingRatio = float.Parse(sn.Value);
                                    break;

                                case "frequencyhz":
                                    ((DistanceJoint)joint).Frequency = float.Parse(sn.Value);
                                    break;

                                case "length":
                                    ((DistanceJoint)joint).Length = float.Parse(sn.Value);
                                    break;

                                case "localanchora":
                                    ((DistanceJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((DistanceJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;
                                }
                            }
                            break;

                            case JointType.Friction:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "localanchora":
                                    ((FrictionJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((FrictionJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "maxforce":
                                    ((FrictionJoint)joint).MaxForce = float.Parse(sn.Value);
                                    break;

                                case "maxtorque":
                                    ((FrictionJoint)joint).MaxTorque = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Wheel:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "enablemotor":
                                    ((WheelJoint)joint).MotorEnabled = bool.Parse(sn.Value);
                                    break;

                                case "localanchora":
                                    ((WheelJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((WheelJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "motorspeed":
                                    ((WheelJoint)joint).MotorSpeed = float.Parse(sn.Value);
                                    break;

                                case "dampingratio":
                                    ((WheelJoint)joint).DampingRatio = float.Parse(sn.Value);
                                    break;

                                case "maxmotortorque":
                                    ((WheelJoint)joint).MaxMotorTorque = float.Parse(sn.Value);
                                    break;

                                case "frequencyhz":
                                    ((WheelJoint)joint).Frequency = float.Parse(sn.Value);
                                    break;

                                case "axis":
                                    ((WheelJoint)joint).Axis = ReadVector(sn);
                                    break;
                                }
                            }
                            break;

                            case JointType.Prismatic:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "enablelimit":
                                    ((PrismaticJoint)joint).LimitEnabled = bool.Parse(sn.Value);
                                    break;

                                case "enablemotor":
                                    ((PrismaticJoint)joint).MotorEnabled = bool.Parse(sn.Value);
                                    break;

                                case "localanchora":
                                    ((PrismaticJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((PrismaticJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "axis":
                                    ((PrismaticJoint)joint).Axis = ReadVector(sn);
                                    break;

                                case "maxmotorforce":
                                    ((PrismaticJoint)joint).MaxMotorForce = float.Parse(sn.Value);
                                    break;

                                case "motorspeed":
                                    ((PrismaticJoint)joint).MotorSpeed = float.Parse(sn.Value);
                                    break;

                                case "lowertranslation":
                                    ((PrismaticJoint)joint).LowerLimit = float.Parse(sn.Value);
                                    break;

                                case "uppertranslation":
                                    ((PrismaticJoint)joint).UpperLimit = float.Parse(sn.Value);
                                    break;

                                case "referenceangle":
                                    ((PrismaticJoint)joint).ReferenceAngle = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Pulley:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "worldanchora":
                                    ((PulleyJoint)joint).WorldAnchorA = ReadVector(sn);
                                    break;

                                case "worldanchorb":
                                    ((PulleyJoint)joint).WorldAnchorB = ReadVector(sn);
                                    break;

                                case "lengtha":
                                    ((PulleyJoint)joint).LengthA = float.Parse(sn.Value);
                                    break;

                                case "lengthb":
                                    ((PulleyJoint)joint).LengthB = float.Parse(sn.Value);
                                    break;

                                case "localanchora":
                                    ((PulleyJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((PulleyJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "ratio":
                                    ((PulleyJoint)joint).Ratio = float.Parse(sn.Value);
                                    break;

                                case "constant":
                                    ((PulleyJoint)joint).Constant = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Revolute:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "enablelimit":
                                    ((RevoluteJoint)joint).LimitEnabled = bool.Parse(sn.Value);
                                    break;

                                case "enablemotor":
                                    ((RevoluteJoint)joint).MotorEnabled = bool.Parse(sn.Value);
                                    break;

                                case "localanchora":
                                    ((RevoluteJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((RevoluteJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "maxmotortorque":
                                    ((RevoluteJoint)joint).MaxMotorTorque = float.Parse(sn.Value);
                                    break;

                                case "motorspeed":
                                    ((RevoluteJoint)joint).MotorSpeed = float.Parse(sn.Value);
                                    break;

                                case "lowerangle":
                                    ((RevoluteJoint)joint).LowerLimit = float.Parse(sn.Value);
                                    break;

                                case "upperangle":
                                    ((RevoluteJoint)joint).UpperLimit = float.Parse(sn.Value);
                                    break;

                                case "referenceangle":
                                    ((RevoluteJoint)joint).ReferenceAngle = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Weld:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "localanchora":
                                    ((WeldJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((WeldJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;
                                }
                            }
                            break;

                            case JointType.Rope:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "localanchora":
                                    ((RopeJoint)joint).LocalAnchorA = ReadVector(sn);
                                    break;

                                case "localanchorb":
                                    ((RopeJoint)joint).LocalAnchorB = ReadVector(sn);
                                    break;

                                case "maxlength":
                                    ((RopeJoint)joint).MaxLength = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Gear:
                                throw new Exception("Gear joint is unsupported");

                            case JointType.Angle:
                            {
                                switch (sn.Name.ToLower())
                                {
                                case "biasfactor":
                                    ((AngleJoint)joint).BiasFactor = float.Parse(sn.Value);
                                    break;

                                case "maximpulse":
                                    ((AngleJoint)joint).MaxImpulse = float.Parse(sn.Value);
                                    break;

                                case "softness":
                                    ((AngleJoint)joint).Softness = float.Parse(sn.Value);
                                    break;

                                case "targetangle":
                                    ((AngleJoint)joint).TargetAngle = float.Parse(sn.Value);
                                    break;
                                }
                            }
                            break;

                            case JointType.Motor:
                                switch (sn.Name.ToLower())
                                {
                                case "angularoffset":
                                    ((MotorJoint)joint).AngularOffset = float.Parse(sn.Value);
                                    break;

                                case "linearoffset":
                                    ((MotorJoint)joint).LinearOffset = ReadVector(sn);
                                    break;

                                case "maxforce":
                                    ((MotorJoint)joint).MaxForce = float.Parse(sn.Value);
                                    break;

                                case "maxtorque":
                                    ((MotorJoint)joint).MaxTorque = float.Parse(sn.Value);
                                    break;

                                case "correctionfactor":
                                    ((MotorJoint)joint).CorrectionFactor = float.Parse(sn.Value);
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }

            world.ProcessChanges();
        }
Beispiel #28
0
        public static InterconnectionBody TryAddInterconnectionBody(this InterconnectionModel model, int maxTryCount)
        {
            var allSlots = Will.Instance.Bodies.OfType <ConnectionSlotBody>().Where(s => s.Model.IsOccupied == false).ToList();

            while (allSlots.Count > 0 && --maxTryCount > 0)
            {
                var randSlot = allSlots.RandomOrDefault <ConnectionSlotBody>();
                var begPos   = randSlot.State.Position;

                var alignedSlot = allSlots.Where(s => !s.Parent.Equals(randSlot.Parent)).FirstOrDefault(s =>
                {
                    var angle = MathHelper.WrapClamp(s.State.Position.Angular + MathHelper.Pi, 0.0f, MathHelper.TwoPi);

                    var diff = Math.Abs(angle - begPos.Angular);

                    var dist = (begPos.Linear - s.State.Position.Linear).Magnitude;

                    return(diff <= model.MaxMissAlign && dist <= model.MaxDistance);
                });

                if (alignedSlot == null)
                {
                    continue;
                }

                //Aligned slots pair found. Let's build a connection between

                randSlot.Model.IsOccupied    = true;
                alignedSlot.Model.IsOccupied = true;

                var endPos      = alignedSlot.State.Position;
                var centerPos   = (begPos.Linear + endPos.Linear) * 0.5;
                var begToCenter = centerPos - begPos.Linear;
                var connPos     = new ALVector2D(begToCenter.Angle, centerPos);

                var rectBody = CreateRectangle(1, begToCenter.Magnitude * 1.8, 0.00001, connPos);
                var connBody = rectBody.CopyAsInterconnection(randSlot.ModelId);
                connBody.IsCollidable = false;
                connBody.BegSlot      = randSlot;
                connBody.EndSlot      = alignedSlot;

                Will.Instance.RunPauseWilling(false);

                Will.Instance.AddBody(connBody);

                //randSlot.State.Position = new ALVector2D((begToCenter.Angle+begPos.Angular)*0.5, begPos.Linear);
                //alignedSlot.State.Position = new ALVector2D(((-begToCenter).Angle+endPos.Angular)*0.5, endPos.Linear);
                randSlot.State.Position    = new ALVector2D(begToCenter.Angle, begPos.Linear);
                alignedSlot.State.Position = new ALVector2D((-begToCenter).Angle, endPos.Linear);

                var begJoint = new HingeJoint(randSlot, connBody, (2 * centerPos + 8 * begPos.Linear) * 0.1f, new Lifespan())
                {
                    DistanceTolerance = model.MaxDistance * 0.5,
                    Softness          = 10
                };
                var begAngle = new AngleJoint(randSlot, connBody, new Lifespan())
                {
                    Softness = 0.0001, BiasFactor = 0.2f
                };

                var endJoint = new HingeJoint(connBody, alignedSlot, (2 * centerPos + 8 * endPos.Linear) * 0.1f, new Lifespan())
                {
                    DistanceTolerance = model.MaxDistance * 0.5,
                    Softness          = 10
                };
                var endAngle = new AngleJoint(connBody, alignedSlot, new Lifespan())
                {
                    Softness = 0.0001, BiasFactor = 0.2f
                };

                Will.Instance.AddJoint(begJoint);
                Will.Instance.AddJoint(begAngle);
                Will.Instance.AddJoint(endAngle);

                Will.Instance.RunPauseWilling(true);

                return(connBody);
            }

            // Sorry :( Aligned pair not found. Please, try again later.
            return(null);
        }
Beispiel #29
0
        private Vector2 _upperLegSize      = new Vector2(3, 0.5f); //x=width, y=height

        public Spider(World world, Vector2 position)
        {
            DebugMaterial matHead = new DebugMaterial(MaterialType.Face)
            {
                Color = Color.ForestGreen,
                Scale = 2f
            };
            DebugMaterial matBody = new DebugMaterial(MaterialType.Blank)
            {
                Color = Color.YellowGreen
            };
            DebugMaterial matLeg = new DebugMaterial(MaterialType.Blank)
            {
                Color = Color.DarkGreen
            };

            //Load bodies
            Fixture circle = FixtureFactory.CreateCircle(world, SpiderBodyRadius, 0.1f, position, matHead);

            circle.Body.BodyType = BodyType.Dynamic;

            //Left upper leg
            Fixture leftUpper = FixtureFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f,
                                                               circle.Body.Position - new Vector2(SpiderBodyRadius, 0) -
                                                               new Vector2(_upperLegSize.X / 2, 0), matBody);

            leftUpper.Body.BodyType = BodyType.Dynamic;

            //Left lower leg
            Fixture leftLower = FixtureFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f,
                                                               circle.Body.Position - new Vector2(SpiderBodyRadius, 0) -
                                                               new Vector2(_upperLegSize.X, 0) -
                                                               new Vector2(_lowerLegSize.X / 2, 0), matLeg);

            leftLower.Body.BodyType = BodyType.Dynamic;

            //Right upper leg
            Fixture rightUpper = FixtureFactory.CreateRectangle(world, _upperLegSize.X, _upperLegSize.Y, 0.1f,
                                                                circle.Body.Position + new Vector2(SpiderBodyRadius, 0) +
                                                                new Vector2(_upperLegSize.X / 2, 0), matBody);

            rightUpper.Body.BodyType = BodyType.Dynamic;

            //Right lower leg
            Fixture rightLower = FixtureFactory.CreateRectangle(world, _lowerLegSize.X, _lowerLegSize.Y, 0.1f,
                                                                circle.Body.Position + new Vector2(SpiderBodyRadius, 0) +
                                                                new Vector2(_upperLegSize.X, 0) +
                                                                new Vector2(_lowerLegSize.X / 2, 0), matLeg);

            rightLower.Body.BodyType = BodyType.Dynamic;

            //Create joints
            JointFactory.CreateRevoluteJoint(world, circle.Body, leftUpper.Body, new Vector2(SpiderBodyRadius, 0));

            _leftShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, circle.Body, leftUpper.Body);
            _leftShoulderAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, circle.Body, rightUpper.Body, new Vector2(-SpiderBodyRadius, 0));

            _rightShoulderAngleJoint            = JointFactory.CreateAngleJoint(world, circle.Body, rightUpper.Body);
            _rightShoulderAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, leftUpper.Body, leftLower.Body, new Vector2(_upperLegSize.X / 2, 0));
            _leftKneeAngleJoint            = JointFactory.CreateAngleJoint(world, leftUpper.Body, leftLower.Body);
            _leftKneeAngleJoint.MaxImpulse = 3;

            JointFactory.CreateRevoluteJoint(world, rightUpper.Body, rightLower.Body,
                                             -new Vector2(_upperLegSize.X / 2, 0));
            _rightKneeAngleJoint            = JointFactory.CreateAngleJoint(world, rightUpper.Body, rightLower.Body);
            _rightKneeAngleJoint.MaxImpulse = 3;
        }
Beispiel #30
0
        public static DisposeCallback CreateTank(DemoOpenInfo info, Vector2D position, List <Body> result)
        {
            Lifespan avatarLifespan = new Lifespan();

            IShape shape = ShapeFactory.CreateSprite(Cache <SurfacePolygons> .GetItem("tank.png"), 4, 18, 2);

            ObjectIgnorer ignorer  = new ObjectIgnorer();
            Body          tankBody = new Body(new PhysicsState(new ALVector2D(0, 0, 0)),
                                              shape,
                                              300,//new MassInfo(40, Scalar.PositiveInfinity),
                                              new Coefficients(0, 1),
                                              avatarLifespan);

            result.Add(tankBody);
            tankBody.State.Position.Linear += position;
            tankBody.ApplyPosition();

            tankBody.CollisionIgnorer = ignorer;
            BodyGraphic graphic = CreateGraphic(tankBody);

            graphic.ZOrder = 2;
            info.Scene.AddGraphic(graphic);

            Scalar            wheelSize     = 18;
            Scalar            wheelSpacing  = -9;
            Scalar            lenghtPercent = .84f;
            Matrix2x3         ident         = Matrix2x3.Identity;
            BoundingRectangle rect;

            shape.CalcBoundingRectangle(ref ident, out rect);
            Scalar          y         = (rect.Max.Y + 4);
            Body            lastWheel = null;
            BoundingPolygon polygon   = new BoundingPolygon(shape.Vertexes);

            Ray      ray2 = new Ray(new Vector2D(rect.Max.X, y), -Vector2D.YAxis);
            Scalar   y3   = y - polygon.Intersects(ray2);
            Vector2D avatarBarrelOffset = new Vector2D(rect.Max.X + 10, y3);

            CircleShape wheelShape = ShapeFactory.CreateColoredCircle(wheelSize, 30);
            Scalar      force      = 0;

            for (Scalar x = rect.Min.X + wheelSize; x < (rect.Max.X - wheelSize) * lenghtPercent; x += (wheelSize * 2 + wheelSpacing))
            {
                Ray    ray = new Ray(new Vector2D(x, y), -Vector2D.YAxis);
                Scalar y2  = y - polygon.Intersects(ray);



                Vector2D offset = new Vector2D(x, y2);

                Body wheel = new Body(
                    new PhysicsState(new ALVector2D(0, offset + position)),
                    wheelShape,
                    10,
                    new Coefficients(0, 3),//  coefficients.Duplicate(),
                    avatarLifespan);
                result.Add(wheel);

                wheel.CollisionIgnorer = ignorer;
                wheel.AngularDamping   = .9f;
                wheel.Updated         += delegate(object sender, UpdatedEventArgs e)
                {
                    wheel.State.ForceAccumulator.Angular += force;
                };
                info.Scene.AddGraphic(CreateGraphic(wheel));

                HingeJoint joint = new HingeJoint(tankBody, wheel, offset + position, avatarLifespan);
                joint.Softness = .1f;
                info.Scene.Engine.AddJoint(joint);

                if (lastWheel != null)
                {
                    AngleJoint joint2 = new AngleJoint(lastWheel, wheel, avatarLifespan);
                    info.Scene.Engine.AddJoint(joint2);
                }
                lastWheel = wheel;
            }


            CircleShape weaponShape = ShapeFactory.CreateColoredCircle(5, 8);

            //now begins the abuse of anominous delegates (BIG TIME)

            EventHandler <KeyboardEventArgs> keyDownHandler = delegate(object sender, KeyboardEventArgs e)
            {
                switch (e.Key)
                {
                case Key.LeftArrow:
                    force = -1500000;
                    break;

                case Key.RightArrow:
                    force = 1500000;
                    break;

                case Key.Space:

                    Scalar velocity = 2000;

                    Matrix2x3 toWorld       = tankBody.Matrices.ToWorld;
                    Matrix2x2 toWorldNormal = tankBody.Matrices.ToWorldNormal;

                    //  Matrix2D mat = avatarBodies[0].Matrices.ToWorld;
                    Vector2D     direction = toWorldNormal * Vector2D.XAxis;
                    PhysicsState state     = new PhysicsState();
                    state.Position.Linear = toWorld * (avatarBarrelOffset);
                    state.Velocity.Linear = velocity * direction + tankBody.State.Velocity.Linear;

                    Body weapon = new Body(state,
                                           weaponShape,
                                           5,
                                           new Coefficients(1, 1),
                                           new Lifespan(10));
                    //weapon.CollisionIgnorer = tankBody.CollisionIgnorer;

                    weapon.Collided += delegate(object sender2, CollisionEventArgs e2)
                    {
                        if (!weapon.Lifetime.IsExpired)
                        {
                            weapon.Lifetime.IsExpired = true;
                            AddParticles(info, weapon.State.Position.Linear, weapon.State.Velocity.Linear * .5f, 50);
                        }
                    };

                    //  weapon.Collided += weapon_Collided;
                    tankBody.State.Velocity.Linear -= (velocity * weapon.Mass.Mass * tankBody.Mass.MassInv) * direction;
                    info.Scene.AddGraphic(CreateGraphic(weapon));
                    break;
                }
            };
            EventHandler <KeyboardEventArgs> keyUpHandler = delegate(object sender, KeyboardEventArgs e)
            {
                switch (e.Key)
                {
                case Key.LeftArrow:
                    force = 0;
                    break;

                case Key.RightArrow:
                    force = 0;
                    break;
                }
            };

            Events.KeyboardDown += keyDownHandler;
            Events.KeyboardUp   += keyUpHandler;

            return(delegate()
            {
                Events.KeyboardDown -= keyDownHandler;
                Events.KeyboardUp -= keyUpHandler;
            });
        }