Represents a simple non-selfintersecting convex polygon. Create a convex hull from the given array of points.
Inheritance: Shape
Example #1
1
        public Pyramid(World world, Vector2 position, int count, float density)
        {
            Vertices rect = PolygonTools.CreateRectangle(0.5f, 0.5f);
            PolygonShape shape = new PolygonShape(rect, density);

            Vector2 rowStart = position;
            rowStart.Y -= 0.5f + count * 1.1f;

            Vector2 deltaRow = new Vector2(-0.625f, 1.1f);
            const float spacing = 1.25f;

            // Physics
            _boxes = new List<Body>();

            for (int i = 0; i < count; i++)
            {
                Vector2 pos = rowStart;

                for (int j = 0; j < i + 1; j++)
                {
                    Body body = BodyFactory.CreateBody(world);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = pos;
                    body.CreateFixture(shape);
                    _boxes.Add(body);

                    pos.X += spacing;
                }
                rowStart += deltaRow;
            }

            //GFX
            _box = new Sprite(ContentWrapper.PolygonTexture(rect, "Square", ContentWrapper.Blue, ContentWrapper.Gold, ContentWrapper.Black, 1f));
        }
        private PyramidTest()
        {
            //Create ground
            FixtureFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

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

            Vector2 x = new Vector2(-7.0f, 0.75f);
            Vector2 deltaX = new Vector2(0.5625f, 1.25f);
            Vector2 deltaY = new Vector2(1.125f, 0.0f);

            for (int i = 0; i < Count; ++i)
            {
                Vector2 y = x;

                for (int j = i; j < Count; ++j)
                {
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = y;
                    body.CreateFixture(shape);

                    y += deltaY;
                }

                x += deltaX;
            }
        }
Example #3
1
        /// <summary>
        /// Creates a chain.
        /// </summary>
        /// <param name="world">The world.</param>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <param name="linkWidth">The width.</param>
        /// <param name="linkHeight">The height.</param>
        /// <param name="fixStart">if set to <c>true</c> [fix start].</param>
        /// <param name="fixEnd">if set to <c>true</c> [fix end].</param>
        /// <param name="numberOfLinks">The number of links.</param>
        /// <param name="linkDensity">The link density.</param>
        /// <returns></returns>
        public static Path CreateChain(World world, Vector2 start, Vector2 end, float linkWidth, float linkHeight, bool fixStart, bool fixEnd, int numberOfLinks, float linkDensity)
        {
            // Chain start / end
            Path path = new Path();
            path.Add(start);
            path.Add(end);

            // A single chainlink
            PolygonShape shape = new PolygonShape(PolygonTools.CreateRectangle(linkWidth, linkHeight));

            // Use PathManager to create all the chainlinks based on the chainlink created before.
            List<Body> chainLinks = PathManager.EvenlyDistibuteShapesAlongPath(world, path, shape, BodyType.Dynamic, numberOfLinks, linkDensity);

            if (fixStart)
            {
                // Fix the first chainlink to the world
                JointFactory.CreateFixedRevoluteJoint(world, chainLinks[0], new Vector2(0, -(linkHeight / 2)), chainLinks[0].Position);
            }

            if (fixEnd)
            {
                // Fix the last chainlink to the world
                JointFactory.CreateFixedRevoluteJoint(world, chainLinks[chainLinks.Count - 1], new Vector2(0, (linkHeight / 2)), chainLinks[chainLinks.Count - 1].Position);
            }

            // Attach all the chainlinks together with a revolute joint
            PathManager.AttachBodiesWithRevoluteJoint(world, chainLinks, new Vector2(0, -linkHeight), new Vector2(0, linkHeight),
                                                      false, false);

            return (path);
        }
        public NetworkCollisionRemnant(Vector2 position, float size, float angleOfStartForce, int ownerId, Color color, World world, Player creator)
            : base(position, size, color, null, creator)
        {
            OwnerId = ownerId;

            body = BodyFactory.CreateBody(world);
            body.BodyType = BodyType.Dynamic;
            body.Position = ConvertUnits.ToSimUnits(position);
            body.FixedRotation = true;
            body.LinearDamping = 0.8f;

            //Create the vertices that will create the collision shape
            Vertices verts = new Vertices();
            verts.Add(new Vector2(-ConvertUnits.ToSimUnits(size / 2f), ConvertUnits.ToSimUnits(size / 2f)));
            verts.Add(new Vector2(-ConvertUnits.ToSimUnits(size / 2f), -ConvertUnits.ToSimUnits(size / 2f)));
            verts.Add(new Vector2(ConvertUnits.ToSimUnits(size / 2f), -ConvertUnits.ToSimUnits(size / 2f)));
            verts.Add(new Vector2(ConvertUnits.ToSimUnits(size / 2f), ConvertUnits.ToSimUnits(size / 2f)));

            //Create the shape and attach it to the body
            PolygonShape s = new PolygonShape(verts, 0);
            body.CreateFixture(s);
            body.FixtureList[0].IsSensor = true;
            body.UserData = this;

            body.CollidesWith = Category.Cat2;
            body.CollisionCategories = Category.Cat2;
            //body.OnSeparation += body_OnSeparation;

            body.ApplyLinearImpulse(new Vector2((float)Math.Cos(angleOfStartForce),(float)Math.Sin(angleOfStartForce)) * 10f);
        }
Example #5
0
        public Key(Rectangle pos, Map map)
            : base(map)
        {
            Body BodyDec = new Body(map.PhysicalWorld);
            BodyDec.BodyType = BodyType.Static;

            PolygonShape S = new PolygonShape(1f);
            S.SetAsBox(pos.Width / 2, pos.Height / 2);

            Fixture = BodyDec.CreateFixture(S);
            Fixture.Restitution = 1f;
            Fixture.Friction = 10f;

            this.Position = pos;

            SetName("Key");

            LightingEngine LE = (LightingEngine)Renderer.GetRenderEffect("LightingEngine");

            light = new PointLight()
            {
                IsEnabled = true,
                Color = new Vector4(0.95f, .7f, .05f, 1f),
                Power = power,
                LightDecay = 350,
                Position = new Vector3(Position.X, Position.Y, 20),
                Direction = new Vector3(0,0, 0)
            };

            LE.AddLight(light);
        }
Example #6
0
        protected Tank(
            ISoundManager soundManager,
            World world, 
            Collection<IDoodad> doodads, 
            Team team, 
            Vector2 position, 
            float rotation, 
            DoodadFactory doodadFactory)
        {
            this.soundManager = soundManager;
            this.world = world;
            this.doodadFactory = doodadFactory;
            this.doodads = doodads;
            this.body = BodyFactory.CreateBody(world, position, this);
            this.body.Rotation = rotation;
            this.body.BodyType = BodyType.Dynamic;
            this.Team = team;
            this.Heading = rotation;
            this.activeMissiles = new List<Missile>();
            this.powerup = PowerUpType.None;

            var shape = new PolygonShape(0);
            shape.SetAsBox(15 / Constants.PixelsPerMeter, 15 / Constants.PixelsPerMeter);
            var fixture = this.body.CreateFixture(shape);
            fixture.CollisionCategories = this.CollisionCategory;
            fixture.CollidesWith = PhysicsConstants.MissileCategory;
            if (this is PlayerControlledTank)
            {
                fixture.CollidesWith |= PhysicsConstants.ObstacleCategory | PhysicsConstants.PitCategory |
                                        PhysicsConstants.SensorCategory;
            }
        }
        private bool LoadCollider()
        {
            /* find a mesh component to create box from */
            var meshComponent = this.GameObject.Components.FirstOrDefault(c => c is MeshComponent) as MeshComponent;
            if (meshComponent == null)
            {
                return false;
            }

            if (!meshComponent.IsLoaded) meshComponent.Load();

            Vector2 vMin = new Vector2(float.MaxValue, float.MaxValue);
            Vector2 vMax = new Vector2(float.MinValue, float.MinValue);

            foreach (var vertex in meshComponent.Vertices)
            {
                if (vertex.X * GameObject.Scale.X < vMin.X) vMin.X = vertex.X * GameObject.Scale.X;
                if (vertex.X * GameObject.Scale.X > vMax.X) vMax.X = vertex.X * GameObject.Scale.X;

                if (vertex.Y * GameObject.Scale.Y < vMin.Y) vMin.Y = vertex.Y * GameObject.Scale.Y;
                if (vertex.Y * GameObject.Scale.Y > vMax.Y) vMax.Y = vertex.Y * GameObject.Scale.Y;
            }

            var vertices = PolygonTools.CreateRectangle((vMax.X - vMin.X) / 2.0f, (vMax.Y - vMin.Y) / 2);

            CollisionShape = new PolygonShape(vertices, 1.0f);

            return true;
        }
Example #8
0
        public override void LoadContent()
        {
            base.LoadContent();

            World.Gravity = new Vector2(0, 9.82f);

            _border = new Border(World, this, ScreenManager.GraphicsDevice.Viewport);

            /* Bridge */
            //We make a path using 2 points.
            Path bridgePath = new Path();
            bridgePath.Add(new Vector2(-15, 5));
            bridgePath.Add(new Vector2(15, 5));
            bridgePath.Closed = false;

            Vertices box = PolygonTools.CreateRectangle(0.125f, 0.5f);
            PolygonShape shape = new PolygonShape(box, 20);

            _bridgeBodies = PathManager.EvenlyDistributeShapesAlongPath(World, bridgePath, shape,
                                                                        BodyType.Dynamic, 29);
            _bridgeBox =
                new Sprite(ScreenManager.Assets.TextureFromShape(shape, MaterialType.Dots, Color.SandyBrown, 1f));

            //Attach the first and last fixtures to the world
            JointFactory.CreateFixedRevoluteJoint(World, _bridgeBodies[0], new Vector2(0f, -0.5f),
                                                  _bridgeBodies[0].Position);
            JointFactory.CreateFixedRevoluteJoint(World, _bridgeBodies[_bridgeBodies.Count - 1], new Vector2(0, 0.5f),
                                                  _bridgeBodies[_bridgeBodies.Count - 1].Position);

            PathManager.AttachBodiesWithRevoluteJoint(World, _bridgeBodies, new Vector2(0f, -0.5f),
                                                      new Vector2(0f, 0.5f),
                                                      false, true);

            /* Soft body */
            //We make a rectangular path.
            Path rectanglePath = new Path();
            rectanglePath.Add(new Vector2(-6, -11));
            rectanglePath.Add(new Vector2(-6, 1));
            rectanglePath.Add(new Vector2(6, 1));
            rectanglePath.Add(new Vector2(6, -11));
            rectanglePath.Closed = true;

            //Creating two shapes. A circle to form the circle and a rectangle to stabilize the soft body.
            List<Shape> shapes = new List<Shape>(2);
            shapes.Add(new PolygonShape(PolygonTools.CreateRectangle(0.5f, 0.5f, new Vector2(-0.1f, 0f), 0f), 1f));
            shapes.Add(new CircleShape(0.5f, 1f));

            //We distribute the shapes in the rectangular path.
            _softBodies = PathManager.EvenlyDistributeShapesAlongPath(World, rectanglePath, shapes,
                                                                      BodyType.Dynamic, 30);
            _softBodyBox =
                new Sprite(ScreenManager.Assets.TextureFromShape(shapes[0], MaterialType.Blank, Color.Silver * 0.8f, 1f));
            _softBodyBox.Origin += new Vector2(ConvertUnits.ToDisplayUnits(0.1f), 0f);
            _softBodyCircle =
                new Sprite(ScreenManager.Assets.TextureFromShape(shapes[1], MaterialType.Waves, Color.Silver, 1f));

            //Attach the bodies together with revolute joints. The rectangular form will converge to a circular form.
            PathManager.AttachBodiesWithRevoluteJoint(World, _softBodies, new Vector2(0f, -0.5f), new Vector2(0f, 0.5f),
                                                      true, true);
        }
Example #9
0
        public override Body CreateBody(World world)
        {
            Int32 count = 0;
            foreach (var key in _resource.TileDefinitionKeys)
            {
                var tileDefinition = (TerrainTileDefinitionResource)ResourceDictionary.GetResource(key);

                if (!String.IsNullOrEmpty(tileDefinition.CollisionHullKey))
                {
                    var vertices = new Vertices((Vector2[])this.ResourceDictionary.GetResource(tileDefinition.CollisionHullKey));

                    var body = new Body(world);
                    _bodies.Add(body);
                    body.BodyType = BodyType.Static;

                    var location = ((ILocatable)_actor).Location;
                    body.Position = new Vector2(((count % _resource.Columns) * _resource.TileWidth + location.X) / Settings.MetersToPixels, ((Int32)(count / _resource.Columns) * _resource.TileHeight + location.Y) / Settings.MetersToPixels);
                    
                    var shape = new PolygonShape(vertices, 0f);
                    var fixture = new Fixture(body, shape, 1.0f);
                    
                    fixture.UserData = new CollisionData { Actor = _actor, Data = tileDefinition.CollisionData };
                }
                
                count++;
            }
            return null;
        }
        private PulleysTest()
        {
            //Ground
            FixtureFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                const float a = 2.0f;
                const float b = 4.0f;
                const float y = 16.0f;
                const float l = 12.0f;

                PolygonShape shape = new PolygonShape(5);
                shape.SetAsBox(a, b);

                Body body1 = BodyFactory.CreateBody(World);
                body1.BodyType = BodyType.Dynamic;
                body1.Position = new Vector2(-10.0f, y);
                body1.CreateFixture(shape);

                Body body2 = BodyFactory.CreateBody(World);
                body2.BodyType = BodyType.Dynamic;
                body2.Position = new Vector2(10.0f, y);

                body2.CreateFixture(shape);

                Vector2 anchor1 = new Vector2(-10.0f, y + b);
                Vector2 anchor2 = new Vector2(10.0f, y + b);
                Vector2 groundAnchor1 = new Vector2(-10.0f, y + b + l);
                Vector2 groundAnchor2 = new Vector2(10.0f, y + b + l);
                _joint1 = new PulleyJoint(body1, body2, groundAnchor1, groundAnchor2, body1.GetLocalPoint(anchor1),
                                          body2.GetLocalPoint(anchor2), 2.0f);
                World.AddJoint(_joint1);
            }
        }
Example #11
0
        private PrismaticTest()
        {
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            PolygonShape shape = new PolygonShape(5);
            shape.Vertices = PolygonTools.CreateRectangle(2.0f, 0.5f);

            Body body = BodyFactory.CreateBody(World);
            body.BodyType = BodyType.Dynamic;
            body.Position = new Vector2(-10.0f, 10.0f);
            body.Rotation = 0.5f * Settings.Pi;
            body.CreateFixture(shape);

            // Bouncy limit
            Vector2 axis = new Vector2(2.0f, 1.0f);
            axis.Normalize();
            _joint = new PrismaticJoint(ground, body, Vector2.Zero, axis);

            // Non-bouncy limit
            //_joint = new PrismaticJoint(ground, body2, body2.Position, new Vector2(-10.0f, 10.0f), new Vector2(1.0f, 0.0f));

            _joint.MotorSpeed = 5.0f;
            _joint.MaxMotorForce = 1000.0f;
            _joint.MotorEnabled = true;
            _joint.LowerLimit = -10.0f;
            _joint.UpperLimit = 20.0f;
            _joint.LimitEnabled = true;

            World.AddJoint(_joint);
        }
Example #12
0
        public override Body CreateBody(World world)
        {
            var unitHull = (Vector2[])ResourceDictionary.GetResource("UnitHull");

            var scaledVertices = new List<Vector2>();
            foreach (var vertex in unitHull)
            {
                scaledVertices.Add(new Vector2(vertex.X * _resource.Width, vertex.Y * _resource.Height));
            }
            
            var vertices = new Vertices(scaledVertices);

            var body = new Body(world);
            body.BodyType = BodyType.Static;
            
            var location = ((ILocatable)_actor).Location;
            body.Position = new Vector2(location.X, location.Y);

            var shape = new PolygonShape(vertices, 1f);

            var fixture = body.CreateFixture(shape, 0f);
            fixture.UserData = new CollisionData { Actor = _actor };
            fixture.CollisionGroup = _resource.CollisionGroup;            
            fixture.OnCollision += OnCollision;
            _body = body;
            return body;
        }
Example #13
0
        public Chest(Rectangle r,Map m)
            : base(m)
        {
            Body BodyDec = new Body(m.PhysicalWorld);
            BodyDec.BodyType = BodyType.Static;

            PolygonShape S = new PolygonShape(1f);
            S.SetAsBox(r.Width / 2, r.Height / 2);

            Fixture = BodyDec.CreateFixture(S);
            Fixture.Restitution = 1f;
            Fixture.Friction = 10f;

            Position = r;

            SetName("Chest");

            items = new List<Item>();

            ChestWindow = new Window(GeneralManager.GetPartialRect(0.4f, 0.2f, 0.2f, 0.6f));
            ChestWindow.BgTex = GeneralManager.Textures["GUI/InGameGUI/ChestMenuBg"];

            ChestWindow.Visible = false;

            CloseButton = new Button(new Rectangle(ChestWindow.Position.Width - 32, 8, 24, 24), "", GeneralManager.Textures["GUI/InGameGUI/CloseButton"], Color.Gray, Color.White, null);
            CloseButton.Action = CloseChestWindow;
            ChestWindow.AddGUI(CloseButton );

            list = new ListBox(new Rectangle(16,16,ChestWindow.Position.Width - 24,ChestWindow.Position.Height - 32));
            ChestWindow.AddGUI(list);

            Map.Parent.AddGUI(ChestWindow);
        }
Example #14
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);
        }
Example #15
0
        private PulleysTest()
        {
            //Ground
            Body ground = BodyFactory.CreateBody(World);
            FixtureFactory.AttachCircle(2, 0, ground, new Vector2(-10.0f, Y + B + L));
            FixtureFactory.AttachCircle(2, 0, ground, new Vector2(10.0f, Y + B + L));

            {
                PolygonShape shape = new PolygonShape(5);
                shape.Vertices = PolygonTools.CreateRectangle(A, B);

                Body body1 = BodyFactory.CreateBody(World);
                body1.BodyType = BodyType.Dynamic;
                body1.Position = new Vector2(-10.0f, Y);
                body1.CreateFixture(shape);

                Body body2 = BodyFactory.CreateBody(World);
                body2.BodyType = BodyType.Dynamic;
                body2.Position = new Vector2(10.0f, Y);

                body2.CreateFixture(shape);

                Vector2 anchor1 = new Vector2(-10.0f, Y + B);
                Vector2 anchor2 = new Vector2(10.0f, Y + B);
                Vector2 groundAnchor1 = new Vector2(-10.0f, Y + B + L);
                Vector2 groundAnchor2 = new Vector2(10.0f, Y + B + L);
                _joint1 = new PulleyJoint(body1, body2, anchor1, anchor2, groundAnchor1, groundAnchor2, 1.5f, true);
                World.AddJoint(_joint1);
            }
        }
Example #16
0
        public override void LoadContent()
        {
            _agent = new Agent(World, new Vector2(5, 10));

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

            Vector2 x = new Vector2(-8.0f, -17.0f);
            Vector2 deltaX = new Vector2(0.5625f, 1.25f);
            Vector2 deltaY = new Vector2(1.125f, 0.0f);

            for (int i = 0; i < PyramidBaseBodyCount; ++i)
            {
                Vector2 y = x;

                for (int j = i; j < PyramidBaseBodyCount; ++j)
                {
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = y;
                    body.CreateFixture(shape);

                    y += deltaY;
                }

                x += deltaX;
            }

            base.LoadContent();
        }
Example #17
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);
            }

            {
                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, 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);

                //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);
            }
        }
Example #18
0
 public Goalie(World world, GoalieData spawn)
 {
     var body = new Body(world);
     var angle = spawn.End - spawn.Begin;
     body.Rotation = FMath.Atan2(angle.Y, angle.X);
     segment.A = spawn.Begin;
     segment.B = spawn.End;
     var normal = new Vector2(-angle.Y, angle.X);
     normal.Normalize();
     delta = normal * .5f;
     segmentOut.A = spawn.Begin + delta;
     segmentOut.B = spawn.End + delta;
     segmentIn.A = spawn.Begin - delta;
     segmentIn.B = spawn.End - delta;
     body.Position = spawn.Begin;
     var verts = new Vertices();
     verts.Add(new Vector2(left, bottom));
     verts.Add(new Vector2(right, bottom));
     verts.Add(new Vector2(right, top));
     verts.Add(new Vector2(left, top));
     var shape = new PolygonShape(verts, 1f);
     body.FixedRotation = true;
     body.BodyType = BodyType.Dynamic;
     Fixture = body.CreateFixture(shape);
 }
        private OneSidedPlatformTest()
        {
            //Ground
            BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            // Platform
            {
                Body body = BodyFactory.CreateBody(World);
                body.Position = new Vector2(0.0f, 10.0f);

                PolygonShape shape = new PolygonShape(1);
                shape.SetAsBox(3.0f, 0.5f);
                _platform = body.CreateFixture(shape);

                _top = 10.0f + 0.5f;
            }

            // Actor
            {
                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(0.0f, 12.0f);

                _radius = 0.5f;
                CircleShape shape = new CircleShape(_radius, 20);
                _character = body.CreateFixture(shape);

                body.LinearVelocity = new Vector2(0.0f, -50.0f);
            }
        }
Example #20
0
 public static Fixture AttachRectangle(float width, float height, float density, Vector2 offset, Body body, object userData = null)
 {
     Vertices rectangleVertices = PolygonTools.CreateRectangle(width / 2, height / 2);
     rectangleVertices.Translate(ref offset);
     PolygonShape rectangleShape = new PolygonShape(rectangleVertices, density);
     return body.CreateFixture(rectangleShape, userData);
 }
Example #21
0
        private WheelJointTest()
        {
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            {
                PolygonShape shape = new PolygonShape(1);
                shape.Vertices = PolygonTools.CreateRectangle(0.5f, 2.0f);

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

                body.CreateFixture(shape);

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

                WheelJoint jd = new WheelJoint(ground, body, new Vector2(0, 8.5f), axis);
                jd.MotorSpeed = 1.0f;
                jd.MaxMotorTorque = 1000.0f;
                jd.MotorEnabled = true;
                jd.SpringFrequencyHz = 1.0f;
                jd.SpringDampingRatio = 0.2f;
                World.AddJoint(jd);

                PolygonShape shape2 = new PolygonShape(1);
                shape2.Vertices = PolygonTools.CreateRectangle(0.5f, 2.0f);
                Body body2 = BodyFactory.CreatePolygon(World, shape2.Vertices, 0.5f);
                body2.BodyType = BodyType.Dynamic;
                body2.Position = new Vector2(10.0f, 7.0f);
            }
        }
Example #22
0
        public override void Update(GameSettings settings, GameTime gameTime)
        {
            base.Update(settings, gameTime);

            PolygonShape shape = new PolygonShape(new Vertices(_points), 0f);

            DrawString("Press g to generate a new random convex hull");

            DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View);
            DebugView.DrawPolygon(shape.Vertices.ToArray(), shape.Vertices.Count, new Color(0.9f, 0.9f, 0.9f));

            for (int i = 0; i < _count; ++i)
            {
                DebugView.DrawPoint(_points[i], 0.1f, new Color(0.9f, 0.5f, 0.5f));
                Vector2 position = GameInstance.ConvertWorldToScreen(_points[i]);
                DebugView.DrawString((int)position.X, (int)position.Y, i.ToString());
            }

            DebugView.EndCustomDraw();

            if (_auto)
            {
                Generate();
            }
        }
Example #23
0
        public override Body CreateBody(World world)
        {
            var unithull = new Vertices((Vector2[])this.ResourceDictionary.GetResource(_resource.CollisionHullKey));
            
            var scaledVertices = new List<Vector2>();
            foreach (var vertex in unithull)
            {
                scaledVertices.Add(new Vector2(vertex.X * _resource.Width, vertex.Y * _resource.Height));
            }

            var vertices = new Vertices(scaledVertices);

            var body = new Body(world);
            body.BodyType = BodyType.Dynamic;
            body.IgnoreGravity = true;
            body.LinearDamping = 0.0f;
            body.FixedRotation = true;
            body.Mass = 0;
            var location = ((ILocatable)_actor).Location;
            body.Position = new Vector2(location.X, location.Y);

            var shape = new PolygonShape(vertices, 1f);

            var fixture = body.CreateFixture(shape, 0f);
            fixture.CollisionGroup = _resource.CollisionGroup;
            fixture.UserData = new CollisionData { Actor = _actor };
            fixture.OnCollision += OnCollision;
            _body = body;
            return body;
        }
Example #24
0
        public RedAlarmLamp(Rectangle r, Map m)
            : base(m)
        {
            Body BodyDec = new Body(m.PhysicalWorld);
            BodyDec.BodyType = BodyType.Static;

            PolygonShape S = new PolygonShape(1f);
            S.SetAsBox(r.Width / 2, r.Height / 2);

            Fixture = BodyDec.CreateFixture(S);
            Fixture.Restitution = 1f;
            Fixture.Friction = 10f;

            Position = r;

            SetName("RedAlarmLamp");

            AlertLight = new SpotLight()
            {
                IsEnabled = true,
                Color = new Vector4(0.9f, .1f, .1f, 1f),
                Power = .6f,
                LightDecay = 600,
                Position = new Vector3(r.X, r.Y, 20),
                SpotAngle = 1.5f,
                SpotDecayExponent = 3,
                Direction = new Vector3(0.244402379f, 0.969673932f, 0)
            };

            LightingEngine LE = (LightingEngine)Renderer.GetRenderEffect("LightingEngine");
            LE.AddLight(AlertLight);
        }
        private SensorTest()
        {
            {
                Body ground = BodyFactory.CreateBody(World);

                {
                    Vertices edge = PolygonTools.CreateEdge(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));
                    PolygonShape shape = new PolygonShape(edge, 1);
                    ground.CreateFixture(shape);
                }

                {
                    CircleShape shape = new CircleShape(5.0f, 1);
                    shape.Position = new Vector2(0.0f, 10.0f);

                    _sensor = ground.CreateFixture(shape);
                    _sensor.IsSensor = true;
                }
            }

            {
                CircleShape shape = new CircleShape(1.0f, 1);

                for (int i = 0; i < Count; ++i)
                {
                    _touching[i] = false;
                    _bodies[i] = BodyFactory.CreateBody(World);
                    _bodies[i].BodyType = BodyType.Dynamic;
                    _bodies[i].Position = new Vector2(-10.0f + 3.0f*i, 20.0f);
                    _bodies[i].UserData = i;

                    _bodies[i].CreateFixture(shape);
                }
            }
        }
 public FarseerObject(FarseerWorld world, Vertices vertices, float density = 1, BodyType BodyType = BodyType.Dynamic)
 {
     Shape shape = new PolygonShape(vertices, density);
     body = new Body(world.World);
     body.BodyType = BodyType;
     body.CreateFixture(shape);
     body.Enabled = false;
 }
Example #27
0
        public override EngineShapes.Shape ToEngineShape()
        {
            var engineShape = new EngineShapes.PolygonShape(ShapeSettings.DefaultDensity);

            engineShape.Set(new Vertices(
                                Points.Select(p => (p - Center).ToSimulation()).ToList()));
            return(engineShape);
        }
Example #28
0
		public static Fixture AttachPolygon( Vertices vertices, float density, Body body, object userData = null )
		{
			if( vertices.Count <= 1 )
				throw new ArgumentOutOfRangeException( nameof( vertices ), "Too few points to be a polygon" );

			var polygon = new PolygonShape( vertices, density );
			return body.createFixture( polygon, userData );
		}
Example #29
0
        public Missile(Ship parent, Vector2 offset, Vector2 speed, string texture)
            : base(parent, texture, parent.Size)
        {
            #region Body Initialize
            Body = new Body(State.World);
            Body.BodyType = BodyType.Dynamic;
            Body.IsBullet = true;
            Body.LinearDamping = 1;
            Body.AngularDamping = 1;

            var size = parent.Size;
            var shape = new PolygonShape(PolygonTools.CreateRectangle(0.05f * size, 0.2f * size, new Vector2(0) * size, 0), 1);
            Body.CreateFixture(shape);
            Body.Position = parent.Body.Position + parent.Body.GetWorldVector(offset);
            Body.Rotation = parent.Body.Rotation;

            Body.OnCollision += (a, b, contact) =>
            {
                if (b.Body.UserData == Parent)
                    return false;

                if (b.Body.UserData is Projectile) // TODO: damage
                    return false;

                var entityB = b.Body.UserData as Entity;
                if (entityB != null)
                    Hit(entityB);

                Dead = true;
                return false;
            };

            Body.LinearVelocity = Parent.Body.LinearVelocity + Parent.Body.GetWorldVector(speed);
            Body.UserData = this;
            #endregion

            var start = Body.Position;
            var point = start + Util.RadarLengthDir(Body.Rotation - (Util.Pi2 / 4), 50);
            var min = 100f;
            Entity entity = null;

            // TODO: use multiple rays
            parent.State.World.RayCast((f, p, n, fr) =>
            {
                if (f.Body == parent.Body || f.Body.UserData is Bullet)
                    return -1;

                if (fr > min)
                    return 1;

                min = fr;
                entity = (Entity)f.Body.UserData;
                return fr;
            }, start, point);

            if (entity is Ship)
                _target = entity;
        }
        private LineJointTest()
        {
            Body ground;
            {
                ground = BodyFactory.CreateBody(World);

                Vertices edge = PolygonTools.CreateEdge(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));
                PolygonShape shape = new PolygonShape(edge, 0);
                ground.CreateFixture(shape);
            }

            //-------------------------
            // FixedLineJoint example
            //-------------------------
            {
                PolygonShape shape = new PolygonShape(PolygonTools.CreateRectangle(0.5f, 2.0f), 1);
                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(0.0f, 7.0f);
                body.CreateFixture(shape);

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

                _fixedLineJoint = new FixedLineJoint(body, new Vector2(0.0f, 8.5f), axis);
                _fixedLineJoint.MotorSpeed = 100.0f;
                _fixedLineJoint.MaxMotorForce = 100.0f;
                _fixedLineJoint.MotorEnabled = false;
                _fixedLineJoint.LowerLimit = -4.0f;
                _fixedLineJoint.UpperLimit = 4.0f;
                _fixedLineJoint.EnableLimit = true;
                World.AddJoint(_fixedLineJoint);
            }

            //-------------------------
            // LineJoint example
            //-------------------------
            {
                PolygonShape shape = new PolygonShape(PolygonTools.CreateRectangle(0.5f, 2.0f), 1);
                Body body = BodyFactory.CreateBody(World);
                body.BodyType = BodyType.Dynamic;
                body.Position = new Vector2(10.0f, 7.0f);
                body.CreateFixture(shape);

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

                Vector2 anchor = new Vector2(0.0f, 1.5f);
                _lineJoint = new LineJoint(ground, body, ground.GetLocalPoint(body.GetWorldPoint(anchor)), anchor, axis);
                _lineJoint.MotorSpeed = 100.0f;
                _lineJoint.MaxMotorForce = 100.0f;
                _lineJoint.MotorEnabled = false;
                _lineJoint.LowerLimit = -4.0f;
                _lineJoint.UpperLimit = 4.0f;
                _lineJoint.EnableLimit = true;
                World.AddJoint(_lineJoint);
            }
        }
        private TilesTest()
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();

            {
                const float a = 0.5f;
                Body ground = BodyFactory.CreateBody(World, new Vector2(0, -a));
                const int N = 200;
                const int M = 10;
                Vector2 position = Vector2.Zero;
                position.Y = 0.0f;
                for (int j = 0; j < M; ++j)
                {
                    position.X = -N * a;
                    for (int i = 0; i < N; ++i)
                    {
                        PolygonShape shape = new PolygonShape(0);
                        shape.SetAsBox(a, a, position, 0.0f);
                        Fixture fix = ground.CreateFixture(shape);
                        ++_fixtureCount;
                        position.X += 2.0f * a;
                    }
                    position.Y -= 2.0f * a;
                }
            }

            {
                const float a = 0.5f;
                Vertices box = PolygonTools.CreateRectangle(a, a);
                PolygonShape shape = new PolygonShape(box, 5);

                Vector2 x = new Vector2(-7.0f, 0.75f);
                Vector2 deltaX = new Vector2(0.5625f, 1.25f);
                Vector2 deltaY = new Vector2(1.125f, 0.0f);

                for (int i = 0; i < Count; ++i)
                {
                    Vector2 y = x;

                    for (int j = i; j < Count; ++j)
                    {
                        Body body = BodyFactory.CreateBody(World);
                        body.BodyType = BodyType.Dynamic;
                        body.Position = y;
                        body.CreateFixture(shape);
                        ++_fixtureCount;
                        y += deltaY;
                    }

                    x += deltaX;
                }
            }

            timer.Stop();
            _createTime = timer.ElapsedMilliseconds;
        }
Example #32
0
        public override bool TestPoint(Vector2 point)
        {
            var test = new EngineShapes.PolygonShape(1.0f);

            test.Set(new Vertices(
                         Points.Select(x => new Xna.Vector2(x.X, x.Y)).ToList()));

            var transform = new Transform();

            transform.SetIdentity();
            var mouseXna = new Xna.Vector2(point.X, point.Y);

            return(test.TestPoint(ref transform, ref mouseXna));
        }
Example #33
0
        public override EngineShapes.Shape ToEngineShape()
        {
            var offset = Offset - Center;
            var shape  = new EngineShapes.PolygonShape(ShapeSettings.DefaultDensity);

            shape.Set(new Vertices(new[]
            {
                offset.ToSimulation(),
                (offset + new Vector2(Size.X, 0)).ToSimulation(),
                (offset + Size).ToSimulation(),
                (offset + new Vector2(0, Size.Y)).ToSimulation(),
            }));
            return(shape);
        }