A revolute joint rains to bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated.
Inheritance: Joint
Ejemplo n.º 1
0
		public static RevoluteJoint CreateRevoluteJoint( World world, Body bodyA, Body bodyB, Vector2 anchor )
		{
			var localanchorA = bodyA.getLocalPoint( bodyB.getWorldPoint( anchor ) );
			var joint = new RevoluteJoint( bodyA, bodyB, localanchorA, anchor );
			world.addJoint( joint );
			return joint;
		}
Ejemplo n.º 2
0
 public RopeGrabComponent(int entityId, RopeComponent ropeComponent, RevoluteJoint joint, float progress)
 {
     _entityId = entityId;
     _ropeComponent = ropeComponent;
     _joint = joint;
     _progress = progress;
 }
Ejemplo n.º 3
0
        private void CreatePlayerPhysicsObjects(Vector2 gameWorldPosition)
        {
            MainFixture = FixtureFactory.CreateRectangle(Engine.Physics.World, 0.5f, 0.5f, 1);
            MainFixture.CollisionFilter.CollisionCategories = (Category)(Global.CollisionCategories.Player);
            Bodies.Add(MainFixture.Body);
            MainFixture.Body.Position = Engine.Physics.PositionToPhysicsWorld(gameWorldPosition);
            MainFixture.Body.BodyType = BodyType.Dynamic;
            MainFixture.Body.SleepingAllowed = false;

            WheelFixture = FixtureFactory.CreateCircle(Engine.Physics.World, 0.3f, 1.0f);
            WheelFixture.CollisionFilter.CollisionCategories = (Category)(Global.CollisionCategories.Player);
            Bodies.Add(WheelFixture.Body);
            WheelFixture.Body.Position = MainFixture.Body.Position + new Vector2(0.0f, 0.6f);
            WheelFixture.Body.BodyType = BodyType.Dynamic;

            WheelFixture.Body.SleepingAllowed = false;
            WheelFixture.Friction = 0.5f;

            playerFAJ = JointFactory.CreateFixedAngleJoint(Engine.Physics.World, MainFixture.Body);
            playerFAJ.BodyB = WheelFixture.Body;

            wheelMotorRevJoint = JointFactory.CreateRevoluteJoint(MainFixture.Body, WheelFixture.Body, Vector2.Zero);
            wheelMotorRevJoint.MaxMotorTorque = 10.0f;
            wheelMotorRevJoint.MotorEnabled = true;
            Engine.Physics.World.AddJoint(wheelMotorRevJoint);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a revolute joint and adds it to the world
 /// </summary>
 /// <param name="world"></param>
 /// <param name="bodyA"></param>
 /// <param name="bodyB"></param>
 /// <param name="anchorB"></param>
 /// <returns></returns>
 public static RevoluteJoint CreateRevoluteJoint(World world, Body bodyA, Body bodyB, Vector2 anchorB)
 {
     Vector2 localanchorA = bodyA.GetLocalPoint(bodyB.GetWorldPoint(anchorB));
     RevoluteJoint joint = new RevoluteJoint(bodyA, bodyB, localanchorA, anchorB);
     world.AddJoint(joint);
     return joint;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Attaches the bodies with revolute joints.
        /// </summary>
        /// <param name="world">The world.</param>
        /// <param name="bodies">The bodies.</param>
        /// <param name="localAnchorA">The local anchor A.</param>
        /// <param name="localAnchorB">The local anchor B.</param>
        /// <param name="connectFirstAndLast">if set to <c>true</c> [connect first and last].</param>
        /// <param name="collideConnected">if set to <c>true</c> [collide connected].</param>
        public static List<RevoluteJoint> AttachBodiesWithRevoluteJoint(World world, List<Body> bodies,
                                                                        Vector2 localAnchorA,
                                                                        Vector2 localAnchorB, bool connectFirstAndLast,
                                                                        bool collideConnected)
        {
            List<RevoluteJoint> joints = new List<RevoluteJoint>(bodies.Count + 1);

            for (int i = 1; i < bodies.Count; i++)
            {
                RevoluteJoint joint = new RevoluteJoint(bodies[i], bodies[i - 1], localAnchorA, localAnchorB);
                joint.CollideConnected = collideConnected;
                world.AddJoint(joint);
                joints.Add(joint);
            }

            if (connectFirstAndLast)
            {
                RevoluteJoint lastjoint = new RevoluteJoint(bodies[0], bodies[bodies.Count - 1], localAnchorA,
                                                            localAnchorB);
                lastjoint.CollideConnected = collideConnected;
                world.AddJoint(lastjoint);
                joints.Add(lastjoint);
            }

            return joints;
        }
Ejemplo n.º 6
0
        private Tumbler()
        {
            var ground = BodyFactory.CreateBody(World);

            var body = BodyFactory.CreateBody(World);
            body.BodyType = BodyType.Dynamic;
            body.Position = new Vector2(0.0f, 10.0f);

            PolygonShape shape = new PolygonShape(5);
            shape.SetAsBox(0.5f, 10.0f, new Vector2(10.0f, 0.0f), 0.0f);
            body.CreateFixture(shape);

            shape.SetAsBox(0.5f, 10.0f, new Vector2(-10.0f, 0.0f), 0.0f);
            body.CreateFixture(shape);

            shape.SetAsBox(10.0f, 0.5f, new Vector2(0.0f, 10.0f), 0.0f);
            body.CreateFixture(shape);

            shape.SetAsBox(10.0f, 0.5f, new Vector2(0.0f, -10.0f), 0.0f);
            body.CreateFixture(shape);

            var jd = new RevoluteJoint(ground, body, new Vector2(0.0f, 10.0f), new Vector2(0.0f, 0.0f));
            jd.ReferenceAngle = 0.0f;
            jd.MotorSpeed = 0.05f * MathHelper.Pi;
            jd.MaxMotorTorque = 1e8f;
            jd.MotorEnabled = true;

            World.AddJoint(jd);
        }
        public HumanoidBody(World world, Vector2 dimensions, object userData)
        {
            _torsoHeight = dimensions.Y - dimensions.X/2f;

            Torso = BodyFactory.CreateRectangle(
                world: world,
                width: dimensions.X,
                height: _torsoHeight,
                density: 1f,
                position: Vector2.UnitX*20,
                userData: userData);

            Torso.BodyType = BodyType.Dynamic;

            Wheel = BodyFactory.CreateCircle(
                world: world,
                radius: dimensions.X/2f,
                density: 1f,
                position: Torso.Position + new Vector2(0, _torsoHeight/2),
                userData: userData);

            Wheel.BodyType = BodyType.Dynamic;
            Wheel.Friction = float.MaxValue;
            Wheel.Restitution = float.MinValue;

            JointFactory.CreateFixedAngleJoint(world, Torso);

            Motor = JointFactory.CreateRevoluteJoint(world, Torso, Wheel, Vector2.Zero);
            Motor.MotorEnabled = true;
            Motor.MaxMotorTorque = 10;
        }
Ejemplo n.º 8
0
        private ChainTest()
        {
            //Ground
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                const float y = 25.0f;
                Body prevBody = ground;
                for (int i = 0; i < 30; ++i)
                {
                    Body body = BodyFactory.CreateRectangle(World, 1.2f, 0.25f, 20, new Vector2(0.5f + i, y));
                    body.BodyType = BodyType.Dynamic;
                    body.Friction = 0.2f;

                    Vector2 anchor = new Vector2(i, y);
                    RevoluteJoint joint = new RevoluteJoint(prevBody, body, anchor, true);

                    //The chain is breakable
                    joint.Breakpoint = 10000f;
                    World.AddJoint(joint);

                    prevBody = body;
                }
            }
        }
Ejemplo n.º 9
0
 public RopeNode(Body body, RevoluteJoint joint, float halfLength)
 {
     _ropeNodeTextures = ropeNodeTextures;
     _body = body;
     _joint = joint;
     _halfLength = halfLength;
 }
Ejemplo n.º 10
0
 public CharacterComponent(int entityId, Body body, Body feet, RevoluteJoint feetJoint, CharacterClass characterClass)
 {
     _entityId = entityId;
     _body = body;
     _feet = feet;
     _feetJoint = feetJoint;
     _characterClass = characterClass;
 }
Ejemplo n.º 11
0
 public CompositePhysicsObject(World world, PhysicsObject physObA, PhysicsObject physObB, Vector2 relativeJointPosition)
 {
     this.physObA = physObA;
     this.physObB = physObB;
     revJoint = JointFactory.CreateRevoluteJoint(world, physObA.fixture.Body, physObB.fixture.Body, ConvertUnits.ToSimUnits(relativeJointPosition));
     physObA.fixture.IgnoreCollisionWith(physObB.fixture);
     physObB.fixture.IgnoreCollisionWith(physObA.fixture);
 }
Ejemplo n.º 12
0
        private RevoluteTest()
        {
            //Ground
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                Body bodyB = BodyFactory.CreateCircle(World, 0.5f, 5f, new Vector2(-10.0f, 20.0f));
                bodyB.BodyType = BodyType.Dynamic;

                const float w = 100.0f;
                bodyB.AngularVelocity = w;
                bodyB.LinearVelocity = new Vector2(-8.0f * w, 0.0f);

                _joint = new RevoluteJoint(ground, bodyB, new Vector2(-10.0f, 12.0f), true);
                _joint.MotorSpeed = 1.0f * Settings.Pi;
                _joint.MaxMotorTorque = 10000.0f;
                _joint.MotorEnabled = false;
                _joint.LowerLimit = -0.25f * Settings.Pi;
                _joint.UpperLimit = 0.5f * Settings.Pi;
                _joint.LimitEnabled = true;
                _joint.CollideConnected = true;

                World.AddJoint(_joint);
            }

            {
                Body ball = BodyFactory.CreateCircle(World, 3.0f, 5.0f, new Vector2(5.0f, 30.0f));
                ball.BodyType = BodyType.Dynamic;
                ball.CollisionCategories = Category.Cat1;

                Vertices polygonVertices = PolygonTools.CreateRectangle(10.0f, 0.2f, new Vector2(-10.0f, 0.0f), 0.0f);

                Body polygonBody = BodyFactory.CreatePolygon(World, polygonVertices, 2, new Vector2(20, 10));
                polygonBody.BodyType = BodyType.Dynamic;
                polygonBody.IsBullet = true;

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

                World.AddJoint(joint);
            }

            // Tests mass computation of a small object far from the origin
            {
                Vertices verts = new Vertices(3);
                verts.Add(new Vector2(17.63f, 36.31f));
                verts.Add(new Vector2(17.52f, 36.69f));
                verts.Add(new Vector2(17.19f, 36.36f));

                Body polyShape = BodyFactory.CreatePolygon(World, verts, 1);
                polyShape.BodyType = BodyType.Dynamic;
            }
        }
Ejemplo n.º 13
0
        private RevoluteTest()
        {
            //Ground
            var ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                //The big fixed wheel
                CircleShape shape = new CircleShape(5.0f, 5);

                Body body = BodyFactory.CreateBody(World);
                body.Position = new Vector2(-10.0f, 15.0f);
                body.BodyType = BodyType.Dynamic;

                body.CreateFixture(shape);

                _fixedJoint = new FixedRevoluteJoint(body, Vector2.Zero, body.Position);
                _fixedJoint.MotorSpeed = 0.25f * Settings.Pi;
                _fixedJoint.MaxMotorTorque = 5000.0f;
                _fixedJoint.MotorEnabled = true;
                World.AddJoint(_fixedJoint);

                // The small gear attached to the big one
                Body body1 = BodyFactory.CreateGear(World, 1.5f, 10, 0.1f, 1, 1);
                body1.Position = new Vector2(-10.0f, 12.0f);
                body1.BodyType = BodyType.Dynamic;

                _joint = new RevoluteJoint(body, body1, body.GetLocalPoint(body1.Position),
                                           Vector2.Zero);
                _joint.MotorSpeed = 1.0f * Settings.Pi;
                _joint.MaxMotorTorque = 5000.0f;
                _joint.MotorEnabled = true;
                _joint.CollideConnected = false;

                World.AddJoint(_joint);

                CircleShape circle_shape = new CircleShape(3.0f, 5);
                var circleBody = BodyFactory.CreateBody(World);
                circleBody.Position = new Vector2(5.0f, 30.0f);
                circleBody.BodyType = BodyType.Dynamic;
                circleBody.CreateFixture(circle_shape);
                PolygonShape polygonShape = new PolygonShape(2.0f);
                polygonShape.SetAsBox(10.0f, 0.2f, new Vector2(-10.0f, 0.0f), 0.0f);
                var polygon_body = BodyFactory.CreateBody(World);
                polygon_body.Position = new Vector2(20.0f, 10.0f);
                polygon_body.BodyType = BodyType.Dynamic;
                polygon_body.IsBullet = true;
                polygon_body.CreateFixture(polygonShape);
                RevoluteJoint rjd = new RevoluteJoint(ground, polygon_body, new Vector2(20.0f, 10.0f));
                rjd.LowerLimit = -0.25f * Settings.Pi;
                rjd.UpperLimit = 0.0f;
                rjd.LimitEnabled = true;
                World.AddJoint(rjd);
            }
        }
Ejemplo n.º 14
0
        private RopeTest()
        {
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                Body prevBody = ground;
                PolygonShape largeShape = new PolygonShape(PolygonTools.CreateRectangle(1.5f, 1.5f), 100);
                PolygonShape smallShape = new PolygonShape(PolygonTools.CreateRectangle(0.5f, 0.125f), 20);

                const int N = 10;
                const float y = 15;

                for (int i = 0; i < N; ++i)
                {
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = new Vector2(0.5f + 1.0f * i, y);

                    if (i == N - 1)
                    {
                        Fixture fixture = body.CreateFixture(largeShape);
                        fixture.Friction = 0.2f;
                        fixture.CollisionCategories = Category.Cat2;
                        fixture.CollidesWith = Category.All & ~Category.Cat2;
                        body.Position = new Vector2(1.0f * i, y);
                        body.AngularDamping = 0.4f;
                    }
                    else
                    {
                        Fixture fixture = body.CreateFixture(smallShape);
                        fixture.Friction = 0.2f;
                        fixture.CollisionCategories = Category.Cat1;
                        fixture.CollidesWith = Category.All & ~Category.Cat2;
                    }

                    Vector2 anchor = new Vector2(i, y);
                    RevoluteJoint jd = new RevoluteJoint(prevBody, body, anchor, true); 
                    jd.CollideConnected = false;

                    World.AddJoint(jd);

                    prevBody = body;
                }

                _rj = new RopeJoint(ground, prevBody, new Vector2(0, y), Vector2.Zero);

                //FPE: The two following lines are actually not needed as FPE sets the MaxLength to a default value
                const float extraLength = 0.01f;
                _rj.MaxLength = N - 1.0f + extraLength;

                World.AddJoint(_rj);
            }
        }
        void physic_wheel_Initialysed(object sender, EventArgs e)
        {

            var RectangleA2 = BodyFactory.CreateRectangle(physic_wheel.world, 999999f, 999999f, 1.0f);
            RectangleA2.BodyType = BodyType.Static;
            RectangleA2.Position = new Vector2(0f, 0f);
            RectangleA2.Rotation = 0f;
            RectangleA2.CollisionCategories = Category.None;

            var joint = new RevoluteJoint(physic_wheel.Body, RectangleA2, physic_wheel.physicWorld.UIToPhysic(wheel_cont, 
                new Point(wheel_cont.RenderSize.Width / 2.0, wheel_cont.RenderSize.Height / 2.0)), true) 
            { MotorEnabled = true, MotorSpeed = -0.2f , MaxMotorTorque = 10};
            physic_wheel.world.AddJoint(joint);
        }
    public override void InitJoint()
    {
        base.InitJoint ();
        //
        Vector3 p0 = BodyB.transform.TransformPoint(new Vector3(LocalAnchorB.x, LocalAnchorB.y, -5f));

        joint = JointFactory.CreateRevoluteJoint(FSWorldComponent.PhysicsWorld, BodyA.PhysicsBody, BodyB.PhysicsBody, BodyB.PhysicsBody.GetLocalPoint(FSHelper.Vector3ToFVector2(p0)));
        joint.CollideConnected = CollideConnected;
        joint.LowerLimit = LowerLimit * Mathf.Deg2Rad;
        joint.UpperLimit = UpperLimit * Mathf.Deg2Rad;
        joint.LimitEnabled = LimitEnabled;
        joint.MaxMotorTorque = MaxMotorTorque;
        joint.MotorSpeed = MotorSpeed;
        joint.MotorEnabled = MotorEnabled;
    }
Ejemplo n.º 17
0
        private BodyTypesTest()
        {
            //Ground
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-20.0f, 0.0f), new Vector2(20.0f, 0.0f));

            // Define attachment
            {
                _attachment = BodyFactory.CreateRectangle(World, 1, 4, 2);
                _attachment.BodyType = BodyType.Dynamic;
                _attachment.Position = new Vector2(0.0f, 3.0f);
            }

            // Define platform
            {
                _platform = BodyFactory.CreateRectangle(World, 8.0f, 1f, 2);
                _platform.BodyType = BodyType.Dynamic;
                _platform.Position = new Vector2(0.0f, 5.0f);
                _platform.Friction = 0.6f;

                RevoluteJoint rjd = new RevoluteJoint(_attachment, _platform, new Vector2(0, 5), true);
                rjd.MaxMotorTorque = 50.0f;
                rjd.MotorEnabled = true;
                World.AddJoint(rjd);

                PrismaticJoint pjd = new PrismaticJoint(ground, _platform, new Vector2(0.0f, 5.0f), new Vector2(1.0f, 0.0f), true);
                pjd.MaxMotorForce = 1000.0f;
                pjd.MotorEnabled = true;
                pjd.LowerLimit = -10.0f;
                pjd.UpperLimit = 10.0f;
                pjd.LimitEnabled = true;

                World.AddJoint(pjd);

                _speed = 3.0f;
            }

            // Create a payload
            {
                Body body = BodyFactory.CreateRectangle(World, 1.5f, 1.5f, 2);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(0.0f, 8.0f);
                body.Friction = 0.6f;
            }
        }
Ejemplo n.º 18
0
        public SwingPlatform(World world, SwingPlatformData swingPlatformData)
        {
            width = swingPlatformData.Width;
            height = swingPlatformData.Height;

            body = BodyFactory.CreateRectangle(world, width, height, 1.0f);
            body.Position = swingPlatformData.Center;
            body.BodyType = BodyType.Dynamic;
            anchor = BodyFactory.CreateCircle(world, 0.1f, 1.0f);
            anchor.Position = swingPlatformData.Center;
            anchor.BodyType = BodyType.Static;

            RevoluteJoint revoluteJoint = new RevoluteJoint(body, anchor, new Vector2(0.0f, 0.0f), new Vector2(0.0f, 0.0f));
            revoluteJoint.LowerLimit = -swingPlatformData.MaxAngle;
            revoluteJoint.UpperLimit = swingPlatformData.MaxAngle;
            revoluteJoint.LimitEnabled = true;
            revoluteJoint.MaxMotorTorque = 10.0f;
            revoluteJoint.MotorSpeed = 0.0f;
            revoluteJoint.MotorEnabled = true;
            world.AddJoint(revoluteJoint);
        }
Ejemplo n.º 19
0
        public Character(Game game, Scene scene, Vector2 position)
            : base(game, scene)
        {
            texture = Game.Content.Load<Texture2D>("zombie");
            ZBuffer = 0f;

            width = Conversion.ToWorld(44);
            height = Conversion.ToWorld(165);

            body = BodyFactory.CreateCircle(scene.World, (width / 2f), 40);
            body.Position = position - Vector2.UnitY * body.FixtureList[0].Shape.Radius / 2 + Vector2.UnitY * (height - width + width / 2.0f) / 2.0f;
            body.BodyType = BodyType.Dynamic;
            body.Friction = float.MaxValue;
            body.UserData = this;
            body.CollisionCategories = ElementCategory.CHARACTER;
            body.SleepingAllowed = false;

            body.OnCollision += new OnCollisionEventHandler(body_OnCollision);
            body.OnSeparation += new OnSeparationEventHandler(body_OnSeparation);

            torso = BodyFactory.CreateRectangle(scene.World, (width), (height - width + width / 2.0f), 40);
            torso.Position = position - Vector2.UnitY * body.FixtureList[0].Shape.Radius / 2;
            torso.BodyType = BodyType.Dynamic;
            torso.FixedRotation = true;
            torso.Friction = 0.0f;
            torso.UserData = this;
            torso.CollisionCategories = ElementCategory.CHARACTER;
            torso.CollidesWith = Category.All & ~ElementCategory.ENERGY;
            torso.SleepingAllowed = false;

            //torso.OnCollision += new OnCollisionEventHandler(torso_OnCollision);
            torso.OnSeparation += new OnSeparationEventHandler(torso_OnSeparation);

            revoluteJoint = new RevoluteJoint(torso, body, new Vector2(0, (height - width + width / 2.0f) / 2.0f), Vector2.Zero);
            revoluteJoint.CollideConnected = false;
            scene.World.AddJoint(revoluteJoint);

            State = new RunningCharacterState(scene, this);
        }
Ejemplo n.º 20
0
        public override Object PlacePhysicsObject(Microsoft.Xna.Framework.Vector2 position, FarseerPhysics.Dynamics.World world)
        {
            List<Fixture> list = world.TestPointAll(position);


            if (pin.Checked && list.Count > 0)
            {
                FixedRevoluteJoint j = new FixedRevoluteJoint(list[0].Body, list[0].Body.GetLocalPoint(position), position);
                if (motorEnabled.Checked)
                {
                    j.MotorEnabled = true;
                    float speed;
                    float maxTorque;
                    if (float.TryParse(motorSpeed.Text, out speed)) j.MotorSpeed = speed;
                    if (float.TryParse(motorTorque.Text, out maxTorque)) j.MaxMotorTorque = maxTorque;
                }

                world.AddJoint(j);
                return j;
            }
            
            if (list.Count > 1)
            {
                RevoluteJoint j = new RevoluteJoint(list[0].Body, list[1].Body, list[0].Body.GetLocalPoint(position), list[1].Body.GetLocalPoint(position));
                if (motorEnabled.Checked)
                {
                    j.MotorEnabled = true;
                    float speed;
                    float maxTorque;
                    if (float.TryParse(motorSpeed.Text, out speed)) j.MotorSpeed = speed;
                    if (float.TryParse(motorTorque.Text, out maxTorque)) j.MaxMotorTorque = maxTorque;
                }
                world.AddJoint(j);
                return j;
            }

            return base.PlacePhysicsObject(position, world);
        }
Ejemplo n.º 21
0
        public Vehicle(Game game, World world, Vector2 position)
        {
            var chassisTexture = new TexturedGameEntity(game, position, 0, "Images/vehicle_body", 1);
            parts = new List<PhysicsGameEntity>();

            var chassisBody = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(chassisTexture.Width), ConvertUnits.ToSimUnits(chassisTexture.Height), 10f, ConvertUnits.ToSimUnits(chassisTexture.Position));
            body = new TexturedPhysicsEntity(game, world, CollisionCategoriesSettings.Vehicle, chassisTexture, chassisBody, new Vector2(chassisTexture.Width/2f, chassisTexture.Height/2f));

            //var bodyVertices = new FileTextureReader(@"VerticesList\vehicle.txt").GetVertices();
            //body = new TexturedPhysicsEntity(game,world,chassisTexture,bodyVertices,BodyType.Dynamic,10f);

            float axisWidth = 5, axisHeight = 50;
            Vector2 axisCentroid = new Vector2(axisWidth/2f, axisHeight/2f);
            PhysicsGameEntity leftAxis = new PhysicsGameEntity(game, world, CollisionCategoriesSettings.Vehicle, BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(axisWidth), ConvertUnits.ToSimUnits(axisHeight), 10f, ConvertUnits.ToSimUnits(new Vector2(body.Position.X - 50, body.Position.Y + 15))), axisCentroid),
                rightAxis = new PhysicsGameEntity(game, world, CollisionCategoriesSettings.Vehicle, BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(axisWidth), ConvertUnits.ToSimUnits(axisHeight), 10f, ConvertUnits.ToSimUnits(new Vector2(body.Position.X + 68, body.Position.Y + 15))), axisCentroid);

            leftAxis.Angle = MathHelper.ToRadians(90);

            leftWheel = new TexturedPhysicsEntity(game, world, CollisionCategoriesSettings.Vehicle, new TexturedGameEntity(game, new Vector2(leftAxis.Position.X, leftAxis.Position.Y + 20), 0, "Images/wheel_left", 1), 10f, BodyType.Static);
            rightWheel = new TexturedPhysicsEntity(game, world, CollisionCategoriesSettings.Vehicle, new TexturedGameEntity(game, new Vector2(rightAxis.Position.X, rightAxis.Position.Y + 20), 0, "Images/wheel_right", 1), 10f, BodyType.Static);
            ApplyToWheels();
            parts.Add(body);
            parts.Add(leftWheel);
            parts.Add(rightWheel);
            parts.Add(leftAxis);
            parts.Add(rightAxis);

            parts.ForEach(p => SetPartDynamics(p.Body));

            leftAxisJoint = JointFactory.CreateRevoluteJoint(world, leftAxis.Body, leftWheel.Body, Vector2.Zero);
            rightAxisJoint = JointFactory.CreateRevoluteJoint(world, rightAxis.Body, rightWheel.Body, Vector2.Zero);

            //body.Body.BodyType = BodyType.Kinematic;
            //JointFactory.CreateDistanceJoint(world, leftWheel.Body, rightWheel.Body, Vector2.Zero, Vector2.Zero);

            JointFactory.CreateWeldJoint(world, body.Body, leftAxis.Body, ConvertUnits.ToSimUnits(leftAxis.Position));// ConvertUnits.ToSimUnits(new Vector2(axis1.Position.X - 40, axis1.Position.Y)), Vector2.Zero);// ConvertUnits.ToSimUnits(new Vector2(0,body.Position.Y)));
            JointFactory.CreateWeldJoint(world, body.Body, rightAxis.Body, ConvertUnits.ToSimUnits(rightAxis.Position));//ConvertUnits.ToSimUnits(new Vector2(axis2.Position.X + 80, axis2.Position.Y)), Vector2.Zero);
        }
        private RevoluteTest()
        {
            //Ground
            FixtureFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                //The big fixed wheel
                CircleShape shape = new CircleShape(5.0f, 5);

                Body body = BodyFactory.CreateBody(World);
                body.Position = new Vector2(0.0f, 15.0f);
                body.BodyType = BodyType.Dynamic;

                body.CreateFixture(shape);

                _fixedJoint = new FixedRevoluteJoint(body, Vector2.Zero, body.Position);
                _fixedJoint.MotorSpeed = 0.25f*Settings.Pi;
                _fixedJoint.MaxMotorTorque = 5000.0f;
                _fixedJoint.MotorEnabled = true;
                World.AddJoint(_fixedJoint);

                // The small gear attached to the big one
                List<Fixture> fixtures = FixtureFactory.CreateGear(World, 1.5f, 10, 0.1f, 1, 1);
                fixtures[0].Body.Position = new Vector2(0.0f, 12.0f);
                fixtures[0].Body.BodyType = BodyType.Dynamic;

                _joint = new RevoluteJoint(body, fixtures[0].Body, body.GetLocalPoint(fixtures[0].Body.Position),
                                           Vector2.Zero);
                _joint.MotorSpeed = 1.0f*Settings.Pi;
                _joint.MaxMotorTorque = 5000.0f;
                _joint.MotorEnabled = true;
                _joint.CollideConnected = false;

                World.AddJoint(_joint);
            }
        }
Ejemplo n.º 23
0
        public override void HandleInput()
        {

            
            InputHelper input = game.inputManager.inputHelper;

            if (input.IsNewButtonPress(MouseButtons.LeftButton))
            {
                Vector2 position = ProjectionHelper.PixelToFarseer(input.MousePosition);

                List<Fixture> list = game.farseerManager.world.TestPointAll(position);


                if (list.Count > 1)
                {
                    RevoluteJoint j = new RevoluteJoint(list[0].Body, list[1].Body, list[0].Body.GetLocalPoint(position), list[1].Body.GetLocalPoint(position));

                    game.farseerManager.world.AddJoint(j);

                    FormManager.Property.setSelectedObject(j);
                }
            }
            
        }
Ejemplo n.º 24
0
        private void CreateBody(World w, float x, float y)
        {
            world = w;

            torso = BodyFactory.CreateRectangle(w, 60 * MainGame.PIXEL_TO_METER, 80 * MainGame.PIXEL_TO_METER, 1f);
            torso.BodyType = BodyType.Dynamic;
            torso.CollisionCategories = Category.Cat1;
            torso.UserData = this;
            legs = BodyFactory.CreateCircle(w, 32 * MainGame.PIXEL_TO_METER, 1f);
            legs.BodyType = BodyType.Dynamic;
            legs.Friction = 5.0f;
            legs.CollisionCategories = Category.Cat1;
            legs.UserData = this;

            this.Position = new Vector2(x, y);

            JointFactory.CreateFixedAngleJoint(w, torso);
            axis = JointFactory.CreateRevoluteJoint(w, torso, legs, Vector2.Zero);
            axis.CollideConnected = false;
            axis.MotorEnabled = true;
            axis.MotorSpeed = 0.0f;
            axis.MaxMotorTorque = 10.0f;
        }
Ejemplo n.º 25
0
        private RopeTest()
        {
            Body ground;
            {
                ground = new Body(World);

                EdgeShape shape = new EdgeShape(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));
                ground.CreateFixture(shape);
            }

            {
                const float y = 15;

                Body prevBody = ground;
                PolygonShape largeShape = new PolygonShape(PolygonTools.CreateRectangle(1.5f, 1.5f), 100);
                PolygonShape smallShape = new PolygonShape(PolygonTools.CreateRectangle(0.5f, 0.125f), 20);

                for (int i = 0; i < Count; ++i)
                {
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = new Vector2(0.5f + 1.0f * i, y);

                    if (i == Count - 1)
                    {
                        Fixture fixture = body.CreateFixture(largeShape);
                        fixture.Friction = 0.2f;
                        fixture.CollisionCategories = Category.Cat2;
                        fixture.CollidesWith = Category.All & ~Category.Cat2;
                        body.Position = new Vector2(1.0f * i, y);
                        body.AngularDamping = 0.4f;
                    }
                    else
                    {
                        Fixture fixture = body.CreateFixture(smallShape);
                        fixture.Friction = 0.2f;
                        fixture.CollisionCategories = Category.Cat1;
                        fixture.CollidesWith = Category.All & ~Category.Cat2;
                    }

                    Vector2 anchor = new Vector2(i, y);
                    RevoluteJoint jd = new RevoluteJoint(prevBody, body, prevBody.GetLocalPoint(ref anchor),
                                                         body.GetLocalPoint(ref anchor));
                    jd.CollideConnected = false;

                    World.AddJoint(jd);

                    prevBody = body;
                }

                _rj = new RopeJoint(ground, prevBody, new Vector2(0, y), Vector2.Zero);
                const float extraLength = 0.01f;
                _rj.MaxLength = Count - 1.0f + extraLength;

                World.AddJoint(_rj);
            }
        }
Ejemplo n.º 26
0
        public void Deserialize(World world, Stream stream)
        {
            world.Clear();

            XMLFragmentElement root = XMLFragmentParser.LoadFromStream(stream);

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

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

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

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

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

                                    foreach (XMLFragmentElement sn in n.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();

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

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

                                                    shape.Set(new Vertices(verts.ToArray()));
                                                }
                                                break;
                                            case "centroid":
                                                shape.MassData.Centroid = ReadVector(sn);
                                                break;
                                        }
                                    }

                                    _shapes.Add(shape);
                                }
                                break;
                            case ShapeType.Edge:
                                {
                                    EdgeShape shape = new EdgeShape();
                                    foreach (XMLFragmentElement sn in n.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;
                        }
                    }
                }
            }

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

                        if (n.Name.ToLower() != "fixture")
                            throw new Exception();

                        foreach (XMLFragmentElement sn in n.Elements)
                        {
                            switch (sn.Name.ToLower())
                            {
                                case "shape":
                                    fixture.Shape = _shapes[int.Parse(sn.Value)];
                                    break;
                                case "density":
                                    fixture.Shape.Density = float.Parse(sn.Value);
                                    break;
                                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;
                                        }
                                    }

                                    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);
                    }
                }
            }

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

                        if (n.Name.ToLower() != "body")
                            throw new Exception();

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

                        foreach (XMLFragmentElement sn in n.Elements)
                        {
                            switch (sn.Name.ToLower())
                            {
                                case "active":
                                    if (bool.Parse(sn.Value))
                                        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 "fixtures":
                                    {
                                        foreach (XMLFragmentElement v in sn.Elements)
                                        {
                                            Fixture blueprint = _fixtures[int.Parse(v.Value)];
                                            Fixture f = new Fixture(body, blueprint.Shape, blueprint.CollisionCategories);
                                            f.Restitution = blueprint.Restitution;
                                            f.UserData = blueprint.UserData;
                                            f.Friction = blueprint.Friction;
                                            f.CollidesWith = blueprint.CollidesWith;
                                            f.CollisionGroup = blueprint.CollisionGroup;
                                        }
                                        break;
                                    }
                            }
                        }

                        _bodies.Add(body);
                    }
                }
            }

            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.Distance:
                                joint = new DistanceJoint();
                                break;
                            case JointType.Friction:
                                joint = new FrictionJoint();
                                break;
                            case JointType.Line:
                                joint = new LineJoint();
                                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.Slider:
                                joint = new SliderJoint();
                                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.Line:
                                    {
                                        switch (sn.Name.ToLower())
                                        {
                                            case "enablemotor":
                                                ((LineJoint)joint).MotorEnabled = bool.Parse(sn.Value);
                                                break;
                                            case "localanchora":
                                                ((LineJoint)joint).LocalAnchorA = ReadVector(sn);
                                                break;
                                            case "localanchorb":
                                                ((LineJoint)joint).LocalAnchorB = ReadVector(sn);
                                                break;
                                            case "motorspeed":
                                                ((LineJoint)joint).MotorSpeed = float.Parse(sn.Value);
                                                break;
                                            case "dampingratio":
                                                ((LineJoint)joint).DampingRatio = float.Parse(sn.Value);
                                                break;
                                            case "maxmotortorque":
                                                ((LineJoint)joint).MaxMotorTorque = float.Parse(sn.Value);
                                                break;
                                            case "frequencyhz":
                                                ((LineJoint)joint).Frequency = float.Parse(sn.Value);
                                                break;
                                            case "localxaxis":
                                                ((LineJoint)joint).LocalXAxis = 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 "local1axis1":
                                                ((PrismaticJoint)joint).LocalXAxis1 = 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 "groundanchora":
                                                ((PulleyJoint)joint).GroundAnchorA = ReadVector(sn);
                                                break;
                                            case "groundanchorb":
                                                ((PulleyJoint)joint).GroundAnchorB = 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 "maxlengtha":
                                                ((PulleyJoint)joint).MaxLengthA = float.Parse(sn.Value);
                                                break;
                                            case "maxlengthb":
                                                ((PulleyJoint)joint).MaxLengthB = float.Parse(sn.Value);
                                                break;
                                            case "ratio":
                                                ((PulleyJoint)joint).Ratio = 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.Slider:
                                    {
                                        switch (sn.Name.ToLower())
                                        {
                                            case "dampingratio":
                                                ((SliderJoint)joint).DampingRatio = float.Parse(sn.Value);
                                                break;
                                            case "frequencyhz":
                                                ((SliderJoint)joint).Frequency = float.Parse(sn.Value);
                                                break;
                                            case "maxlength":
                                                ((SliderJoint)joint).MaxLength = float.Parse(sn.Value);
                                                break;
                                            case "minlength":
                                                ((SliderJoint)joint).MinLength = float.Parse(sn.Value);
                                                break;
                                            case "localanchora":
                                                ((SliderJoint)joint).LocalAnchorA = ReadVector(sn);
                                                break;
                                            case "localanchorb":
                                                ((SliderJoint)joint).LocalAnchorB = ReadVector(sn);
                                                break;
                                        }
                                    }
                                    break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        private BodyTypesTest()
        {
            //Ground
            BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            // Define attachment
            {
                _attachment = BodyFactory.CreateBody(World);
                _attachment.BodyType = BodyType.Dynamic;
                _attachment.Position = new Vector2(0.0f, 3.0f);

                Vertices box = PolygonTools.CreateRectangle(0.5f, 2.0f);
                PolygonShape shape = new PolygonShape(box, 2);
                _attachment.CreateFixture(shape);
            }

            // Define platform
            {
                _platform = BodyFactory.CreateBody(World);
                _platform.BodyType = BodyType.Dynamic;
                _platform.Position = new Vector2(0.0f, 5.0f);

                Vertices box = PolygonTools.CreateRectangle(4.0f, 0.5f);
                PolygonShape shape = new PolygonShape(box, 2);

                Fixture fixture = _platform.CreateFixture(shape);
                fixture.Friction = 0.6f;

                RevoluteJoint rjd = new RevoluteJoint(_attachment, _platform,
                                                      _attachment.GetLocalPoint(_platform.Position),
                                                      Vector2.Zero);
                rjd.MaxMotorTorque = 50.0f;
                rjd.MotorEnabled = true;
                World.AddJoint(rjd);

                //FixedPrismaticJoint pjd = new FixedPrismaticJoint(_platform, new Vector2(0.0f, 5.0f),
                //                                                  new Vector2(1.0f, 0.0f));
                //pjd.MaxMotorForce = 1000.0f;
                //pjd.MotorEnabled = true;
                //pjd.LowerLimit = -10.0f;
                //pjd.UpperLimit = 10.0f;
                //pjd.LimitEnabled = true;

                //World.AddJoint(pjd);

                _speed = 3.0f;
            }

            // Create a payload
            {
                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(0.0f, 8.0f);

                Vertices box = PolygonTools.CreateRectangle(0.75f, 0.75f);
                PolygonShape shape = new PolygonShape(box, 2);

                Fixture fixture = body.CreateFixture(shape);
                fixture.Friction = 0.6f;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Requires two existing revolute or prismatic joints (any combination will work).
        /// The provided joints must attach a dynamic body to a static body.
        /// </summary>
        /// <param name="joint1">The first joint.</param>
        /// <param name="joint2">The second joint.</param>
        /// <param name="ratio">The ratio.</param>
        public GearJoint(Joint joint1, Joint joint2, float ratio = 1f)
        {
            JointType = JointType.Gear;
            Joint1    = joint1;
            Joint2    = joint2;
            Ratio     = ratio;

            _typeA = joint1.JointType;
            _typeB = joint2.JointType;

            Debug.Assert(_typeA == JointType.Revolute || _typeA == JointType.Prismatic || _typeA == JointType.FixedRevolute || _typeA == JointType.FixedPrismatic);
            Debug.Assert(_typeB == JointType.Revolute || _typeB == JointType.Prismatic || _typeB == JointType.FixedRevolute || _typeB == JointType.FixedPrismatic);

            float coordinateA, coordinateB;

            // TODO_ERIN there might be some problem with the joint edges in b2Joint.

            _bodyC = Joint1.BodyA;
            _bodyA = Joint1.BodyB;

            // Get geometry of joint1
            Transform xfA = _bodyA.Xf;
            float     aA  = _bodyA.Sweep.A;
            Transform xfC = _bodyC.Xf;
            float     aC  = _bodyC.Sweep.A;

            if (_typeA == JointType.Revolute)
            {
                RevoluteJoint revolute = (RevoluteJoint)joint1;
                _localAnchorC    = revolute.LocalAnchorA;
                _localAnchorA    = revolute.LocalAnchorB;
                _referenceAngleA = revolute.ReferenceAngle;
                _localAxisC      = Vector2.Zero;

                coordinateA = aA - aC - _referenceAngleA;
            }
            else
            {
                PrismaticJoint prismatic = (PrismaticJoint)joint1;
                _localAnchorC    = prismatic.LocalAnchorA;
                _localAnchorA    = prismatic.LocalAnchorB;
                _referenceAngleA = prismatic.ReferenceAngle;
                _localAxisC      = prismatic.LocalXAxisA;

                Vector2 pC = _localAnchorC;
                Vector2 pA = MathUtils.MulT(xfC.q, MathUtils.Mul(xfA.q, _localAnchorA) + (xfA.p - xfC.p));
                coordinateA = Vector2.Dot(pA - pC, _localAxisC);
            }

            _bodyD = Joint2.BodyA;
            _bodyB = Joint2.BodyB;

            // Get geometry of joint2
            Transform xfB = _bodyB.Xf;
            float     aB  = _bodyB.Sweep.A;
            Transform xfD = _bodyD.Xf;
            float     aD  = _bodyD.Sweep.A;

            if (_typeB == JointType.Revolute)
            {
                RevoluteJoint revolute = (RevoluteJoint)joint2;
                _localAnchorD    = revolute.LocalAnchorA;
                _localAnchorB    = revolute.LocalAnchorB;
                _referenceAngleB = revolute.ReferenceAngle;
                _localAxisD      = Vector2.Zero;

                coordinateB = aB - aD - _referenceAngleB;
            }
            else
            {
                PrismaticJoint prismatic = (PrismaticJoint)joint2;
                _localAnchorD    = prismatic.LocalAnchorA;
                _localAnchorB    = prismatic.LocalAnchorB;
                _referenceAngleB = prismatic.ReferenceAngle;
                _localAxisD      = prismatic.LocalXAxisA;

                Vector2 pD = _localAnchorD;
                Vector2 pB = MathUtils.MulT(xfD.q, MathUtils.Mul(xfB.q, _localAnchorB) + (xfB.p - xfD.p));
                coordinateB = Vector2.Dot(pB - pD, _localAxisD);
            }

            _ratio = ratio;

            _constant = coordinateA + _ratio * coordinateB;

            _impulse = 0.0f;
        }
Ejemplo n.º 29
0
        private PinballTest()
        {
            // Ground body
            Body ground;
            {
                ground = BodyFactory.CreateBody(World);

                Vertices vertices = new Vertices(5);
                vertices.Add(new Vector2(0.0f, -2.0f));
                vertices.Add(new Vector2(8.0f, 6.0f));
                vertices.Add(new Vector2(8.0f, 20.0f));
                vertices.Add(new Vector2(-8.0f, 20.0f));
                vertices.Add(new Vector2(-8.0f, 6.0f));

                ChainShape chain = new ChainShape(vertices, true);
                ground.CreateFixture(chain);
            }

            // Flippers
            {
                Vector2 p1 = new Vector2(-2.0f, 0f);
                Vector2 p2 = new Vector2(2.0f, 0f);

                Body leftFlipper = BodyFactory.CreateBody(World, p1);
                leftFlipper.BodyType = BodyType.Dynamic;
                Body rightFlipper = BodyFactory.CreateBody(World, p2);
                rightFlipper.BodyType = BodyType.Dynamic;

                PolygonShape box = new PolygonShape(1);
                box.Vertices = PolygonTools.CreateRectangle(1.75f, 0.1f);

                leftFlipper.CreateFixture(box);
                rightFlipper.CreateFixture(box);

                _leftJoint = new RevoluteJoint(ground, leftFlipper, p1, Vector2.Zero);
                _leftJoint.MaxMotorTorque = 1000.0f;
                _leftJoint.LimitEnabled = true;
                _leftJoint.MotorEnabled = true;
                _leftJoint.MotorSpeed = 0.0f;
                _leftJoint.LowerLimit = -30.0f * Settings.Pi / 180.0f;
                _leftJoint.UpperLimit = 5.0f * Settings.Pi / 180.0f;
                World.AddJoint(_leftJoint);

                _rightJoint = new RevoluteJoint(ground, rightFlipper, p2, Vector2.Zero);
                _rightJoint.MaxMotorTorque = 1000.0f;
                _rightJoint.LimitEnabled = true;
                _rightJoint.MotorEnabled = true;
                _rightJoint.MotorSpeed = 0.0f;
                _rightJoint.LowerLimit = -5.0f * Settings.Pi / 180.0f;
                _rightJoint.UpperLimit = 30.0f * Settings.Pi / 180.0f;
                World.AddJoint(_rightJoint);
            }

            // Circle character
            {
                _ball = BodyFactory.CreateBody(World, new Vector2(1.0f, 15.0f));
                _ball.BodyType = BodyType.Dynamic;
                _ball.IsBullet = true;
                _ball.CreateFixture(new CircleShape(0.2f, 1.0f));
            }
        }
        private BridgeTest()
        {
            Body ground;
            {
                ground = new Body(World);

                PolygonShape shape = new PolygonShape(0);
                shape.SetAsEdge(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));
                ground.CreateFixture(shape);
            }
            {
                Vertices box = PolygonTools.CreateRectangle(0.5f, 0.125f);
                PolygonShape shape = new PolygonShape(box, 20);

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

                    Fixture fixture = body.CreateFixture(shape);
                    fixture.Friction = 0.2f;

                    Vector2 anchor = new Vector2(-0.5f, 0.0f);
                    RevoluteJoint jd = new RevoluteJoint(prevBody, body,
                                                         prevBody.GetLocalPoint(body.GetWorldPoint(anchor)), anchor);
                    World.AddJoint(jd);

                    prevBody = body;
                }

                Vector2 anchor2 = new Vector2(0.5f, 0.0f);
                RevoluteJoint jd2 = new RevoluteJoint(ground, prevBody,
                                                      ground.GetLocalPoint(prevBody.GetWorldPoint(anchor2)), anchor2);
                World.AddJoint(jd2);
            }

            Vertices vertices = new Vertices(3);
            vertices.Add(new Vector2(-0.5f, 0.0f));
            vertices.Add(new Vector2(0.5f, 0.0f));
            vertices.Add(new Vector2(0.0f, 1.5f));

            for (int i = 0; i < 2; ++i)
            {
                PolygonShape shape = new PolygonShape(vertices, 1);

                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(-8.0f + 8.0f*i, 12.0f);

                body.CreateFixture(shape);
            }

            for (int i = 0; i < 3; ++i)
            {
                CircleShape shape = new CircleShape(0.5f, 1);

                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(-6.0f + 6.0f*i, 10.0f);

                body.CreateFixture(shape);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Requires two existing revolute or prismatic joints (any combination will work).
        /// The provided joints must attach a dynamic body to a static body.
        /// </summary>
        /// <param name="jointA">The first joint.</param>
        /// <param name="jointB">The second joint.</param>
        /// <param name="ratio">The ratio.</param>
        /// <param name="bodyA">The first body</param>
        /// <param name="bodyB">The second body</param>
        public GearJoint(Body bodyA, Body bodyB, Joint jointA, Joint jointB, float ratio = 1f)
        {
            JointType = JointType.Gear;
            BodyA     = bodyA;
            BodyB     = bodyB;
            JointA    = jointA;
            JointB    = jointB;
            Ratio     = ratio;

            _typeA = jointA.JointType;
            _typeB = jointB.JointType;

            Debug.Assert(_typeA == JointType.Revolute || _typeA == JointType.Prismatic || _typeA == JointType.FixedRevolute || _typeA == JointType.FixedPrismatic);
            Debug.Assert(_typeB == JointType.Revolute || _typeB == JointType.Prismatic || _typeB == JointType.FixedRevolute || _typeB == JointType.FixedPrismatic);

            float coordinateA, coordinateB;

            // TODO_ERIN there might be some problem with the joint edges in b2Joint.

            _bodyC = JointA.BodyA;
            _bodyA = JointA.BodyB;

            // Get geometry of joint1
            Transform xfA = _bodyA._xf;
            float     aA  = _bodyA._sweep.A;
            Transform xfC = _bodyC._xf;
            float     aC  = _bodyC._sweep.A;

            if (_typeA == JointType.Revolute)
            {
                RevoluteJoint revolute = (RevoluteJoint)jointA;
                _localAnchorC    = revolute.LocalAnchorA;
                _localAnchorA    = revolute.LocalAnchorB;
                _referenceAngleA = revolute.ReferenceAngle;
                _localAxisC      = Vector2.Zero;

                coordinateA = aA - aC - _referenceAngleA;
            }
            else
            {
                PrismaticJoint prismatic = (PrismaticJoint)jointA;
                _localAnchorC    = prismatic.LocalAnchorA;
                _localAnchorA    = prismatic.LocalAnchorB;
                _referenceAngleA = prismatic.ReferenceAngle;
                _localAxisC      = prismatic.LocalXAxis;

                Vector2 pC = _localAnchorC;
                Vector2 pA = Complex.Divide(Complex.Multiply(ref _localAnchorA, ref xfA.q) + (xfA.p - xfC.p), ref xfC.q);
                coordinateA = Vector2.Dot(pA - pC, _localAxisC);
            }

            _bodyD = JointB.BodyA;
            _bodyB = JointB.BodyB;

            // Get geometry of joint2
            Transform xfB = _bodyB._xf;
            float     aB  = _bodyB._sweep.A;
            Transform xfD = _bodyD._xf;
            float     aD  = _bodyD._sweep.A;

            if (_typeB == JointType.Revolute)
            {
                RevoluteJoint revolute = (RevoluteJoint)jointB;
                _localAnchorD    = revolute.LocalAnchorA;
                _localAnchorB    = revolute.LocalAnchorB;
                _referenceAngleB = revolute.ReferenceAngle;
                _localAxisD      = Vector2.Zero;

                coordinateB = aB - aD - _referenceAngleB;
            }
            else
            {
                PrismaticJoint prismatic = (PrismaticJoint)jointB;
                _localAnchorD    = prismatic.LocalAnchorA;
                _localAnchorB    = prismatic.LocalAnchorB;
                _referenceAngleB = prismatic.ReferenceAngle;
                _localAxisD      = prismatic.LocalXAxis;

                Vector2 pD = _localAnchorD;
                Vector2 pB = Complex.Divide(Complex.Multiply(ref _localAnchorB, ref xfB.q) + (xfB.p - xfD.p), ref xfD.q);
                coordinateB = Vector2.Dot(pB - pD, _localAxisD);
            }

            _ratio    = ratio;
            _constant = coordinateA + _ratio * coordinateB;
            _impulse  = 0.0f;
        }
Ejemplo n.º 32
0
        // Create servo bot entity
        public static int createServoBot(int ownerId, int maxHp)
        {
            int entityId = EntityManager.createEntity();
            PositionComponent ownerPositionComponent = EntityManager.getPositionComponent(ownerId);
            FactionComponent ownerFactionComponent = EntityManager.getFactionComponent(ownerId);
            Vector2 feetOffset = new Vector2(0, 0.25f);
            Body body;
            Body feet;
            RevoluteJoint feetJoint;
            World world = SystemManager.physicsSystem.world;

            body = BodyFactory.CreateRectangle(world, 0.5f, 0.5f, 0.5f, ownerPositionComponent.position);
            body.BodyType = BodyType.Dynamic;
            body.UserData = entityId;
            body.FixedRotation = true;
            body.Friction = 0f;
            body.UserData = entityId;
            body.CollisionCategories = (ushort)CollisionCategory.Characters;
            body.OnCollision += new OnCollisionEventHandler(playerCharacterBodyOnCollision);

            feet = BodyFactory.CreateCircle(world, 0.25f, 1f, ownerPositionComponent.position + feetOffset);
            feet.BodyType = BodyType.Dynamic;
            feet.UserData = entityId;
            feet.Friction = 5f;
            feet.CollisionCategories = (ushort)CollisionCategory.CharacterFeet;
            feet.CollidesWith = (ushort)CollisionCategory.Terrain;

            feetJoint = new RevoluteJoint(body, feet, feetOffset, Vector2.Zero, false);
            feetJoint.MotorEnabled = true;
            feetJoint.MaxMotorTorque = 100f;
            feetJoint.MotorSpeed = 0f;
            world.AddJoint(feetJoint);

            // Owner components
            EntityManager.addComponent(ownerId, new HasProxyComponent(ownerId, entityId));

            // Bot components
            EntityManager.addComponent(entityId, new IsProxyComponent(entityId, ownerId));
            EntityManager.addComponent(entityId, new CharacterComponent(entityId, body, feet, feetJoint, CharacterClass.Fighter));
            EntityManager.addComponent(entityId, new StatsComponent(entityId, maxHp, maxHp, 10, 10, 10, 100));
            EntityManager.addComponent(entityId, new PositionComponent(entityId, body));
            EntityManager.addComponent(entityId, new IgnoreRopeRaycastComponent(entityId));
            EntityManager.addComponent(entityId, new IgnoreBridgeRaycastComponent(entityId));
            EntityManager.addComponent(entityId, new FactionComponent(entityId, ownerFactionComponent.faction, ownerFactionComponent.hostileFaction));
            EntityManager.addComponent(entityId, new RenderHealthComponent(entityId));
            EntityManager.addComponent(entityId, new PerformingSkillsComponent(entityId));
            EntityManager.addComponent(entityId, new ExternalMovementSpeedsComponent(entityId));
            EntityManager.addComponent(entityId, new AffectedBySpellEntitiesComponent(entityId));
            EntityManager.addComponent(entityId, new PhysicsComponent(entityId, new List<Body>(new[] { body, feet })));
            EntityManager.addComponent(entityId, new RestoreProxyPositionTargetComponent(entityId));
            EntityManager.addComponent(entityId, new AnimationComponent(entityId, AnimationCategory.ServoBot, AnimationType.Idle, 3));

            return entityId;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Requires two existing revolute or prismatic joints (any combination will work).
        /// The provided joints must attach a dynamic body to a static body.
        /// </summary>
        /// <param name="jointA">The first joint.</param>
        /// <param name="jointB">The second joint.</param>
        /// <param name="ratio">The ratio.</param>
        public GearJoint(Joint jointA, Joint jointB, float ratio)
            : base(jointA.BodyA, jointA.BodyA)
        {
            this.JointType = JointType.Gear;
            this.JointA    = jointA;
            this.JointB    = jointB;
            this.Ratio     = ratio;

            JointType type1 = jointA.JointType;
            JointType type2 = jointB.JointType;

            // Make sure its the right kind of joint
            Debug.Assert(type1 == JointType.Revolute ||
                         type1 == JointType.Prismatic);
            Debug.Assert(type2 == JointType.Revolute ||
                         type2 == JointType.Prismatic);

            // In the case of a prismatic and revolute joint, the first body must be static.
            if (type1 == JointType.Revolute || type1 == JointType.Prismatic)
            {
                Debug.Assert(jointA.BodyB.BodyType == BodyType.Static);
            }
            if (type2 == JointType.Revolute || type2 == JointType.Prismatic)
            {
                Debug.Assert(jointB.BodyB.BodyType == BodyType.Static);
            }

            float coordinate1 = 0.0f, coordinate2 = 0.0f;

            switch (type1)
            {
            case JointType.Revolute:
                this.BodyA        = jointA.BodyA;
                this._revolute1   = (RevoluteJoint)jointA;
                this.LocalAnchor1 = this._revolute1.LocalAnchorA;
                coordinate1       = this._revolute1.JointAngle;
                break;

            case JointType.Prismatic:
                this.BodyA        = jointA.BodyA;
                this._prismatic1  = (PrismaticJoint)jointA;
                this.LocalAnchor1 = this._prismatic1.LocalAnchorA;
                coordinate1       = this._prismatic1.JointTranslation;
                break;
            }

            switch (type2)
            {
            case JointType.Revolute:
                this.BodyB        = jointB.BodyA;
                this._revolute2   = (RevoluteJoint)jointB;
                this.LocalAnchor2 = this._revolute2.LocalAnchorA;
                coordinate2       = this._revolute2.JointAngle;
                break;

            case JointType.Prismatic:
                this.BodyB        = jointB.BodyA;
                this._prismatic2  = (PrismaticJoint)jointB;
                this.LocalAnchor2 = this._prismatic2.LocalAnchorA;
                coordinate2       = this._prismatic2.JointTranslation;
                break;
            }

            this._ant = coordinate1 + this.Ratio * coordinate2;
        }