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)); }
/// <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 Game(UserControl userControl, Canvas drawingCanvas, Canvas debugCanvas, TextBlock txtDebug) { //Initialize IsActive = true; IsFixedTimeStep = true; TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16); Components = new List<DrawableGameComponent>(); World = new World(new Vector2(0, 0)); _gameTime = new GameTime(); _gameTime.GameStartTime = DateTime.Now; _gameTime.FrameStartTime = DateTime.Now; _gameTime.ElapsedGameTime = TimeSpan.Zero; _gameTime.TotalGameTime = TimeSpan.Zero; //Setup Canvas DrawingCanvas = drawingCanvas; DebugCanvas = debugCanvas; TxtDebug = txtDebug; UserControl = userControl; //Setup GameLoop _gameLoop = new Storyboard(); _gameLoop.Completed += GameLoop; _gameLoop.Duration = TargetElapsedTime; DrawingCanvas.Resources.Add("gameloop", _gameLoop); }
public Melee(Unit owner, World world) : base(owner, world) { Body.Position = owner.Position + new Vector2(-owner.Facing * 2.7f, -0.8f); _startingPosition = Body.Position; Body.ApplyLinearImpulse(new Vector2(-owner.Facing * Speed, 0)); }
//position denotes location IN SIM SPACE public BallExplosion(World world, float intensity, Vector2 position) { particleList = new List<Body>(); destructorWorld = world; particleImage = Game1.ballImage; for (int i = 0; i < numParticles; i++) { //Convert to Radians for Math's sake: angularSpacing = 2 * Math.PI / numParticles; //initialize the particle Body particle = BodyFactory.CreateCircle(world, UnitConverter.toSimSpace(radius), 50f, position); particle.BodyType = BodyType.Dynamic; particle.FixedRotation = true; particle.IsBullet = true; particle.LinearDamping = 0f; particle.GravityScale = .0f; particle.Friction = 0; particle.Restitution = 1.2f; particle.CollisionGroup = -1; //compute the impulse and send the particle on its merry way xVel = UnitConverter.toSimSpace((int)(10 * intensity * Math.Cos(i * angularSpacing))); yVel = UnitConverter.toSimSpace((int)(10 * intensity * Math.Sin(i * angularSpacing))); particle.LinearVelocity = new Vector2((float)xVel, (float)yVel); //Add each particle to a List for summary destruction after explosion particleList.Add(particle); } }
public LocalPlayer(World world, Vector2 position, Category collisionCat, float scale, float limbStrength, float limbDefense, bool evilSkin, Color color, PlayerIndex player) : base(world, position, collisionCat, scale, limbStrength, limbDefense, evilSkin, color) { this.player = player; punchBtnPressed = punchKeyPressed = false; kickBtnPressed = kickKeyPressed = false; shootBtnPressed = shootKeyPressed = false; trapBtnPressed = trapKeyPressed = false; usesKeyboard = !GamePad.GetState(player).IsConnected; lastShootAngle = 0f; jumpBtn = Buttons.A; rightBtn = Buttons.LeftThumbstickRight; leftBtn = Buttons.LeftThumbstickLeft; crouchBtn = Buttons.LeftTrigger; punchBtn = Buttons.X; kickBtn = Buttons.B; shootBtn = Buttons.RightTrigger; trapBtn = Buttons.Y; upKey = Keys.W; rightKey = Keys.D; leftKey = Keys.A; downKey = Keys.S; trapKey = Keys.T; }
public LevelPortal(World nWorld, Level nLevel, ContentManager nContentManager, Color nColor, Vector2 nPos, OnLevelPortalCollision nDelegate, Hashtable nConfig) { string nTextureName = "SpriteMaps/Portal"; base.Init(nWorld, nLevel, nContentManager, nTextureName, nColor, nPos); //Populate the Hashtable SpriteMap with the values for the player spritemap AddFrame(SpriteState.Portal, 0, 0, 100, 100); AddFrame(SpriteState.Portal, 100, 0, 100, 100); AddFrame(SpriteState.Portal, 200, 0, 100, 100); //Default SpriteState SetState(SpriteState.Portal); //Manually step the animation to update the sprite Source rectangle StepAnimation(); //Set callback for collisions Body.OnCollision += OnCollision; Body.OnSeparation += OnSeparation; //Other physical properties Body.BodyType = BodyType.Static; Body.IsSensor = true; Body.CollidesWith = Category.All; Body.CollisionCategories = Category.Cat30; Body.CollisionGroup = 30; Body.SleepingAllowed = false; Body.Position = nPos; OnPortalCollision = nDelegate; mLevelId = (int)nConfig["LevelId"]; }
public static Body CreateCompoundPolygon(World world, List<Vertices> list, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static, object userData = null) { //We create a single body Body polygonBody = CreateBody(world, position, rotation, bodyType); FixtureFactory.AttachCompoundPolygon(list, density, polygonBody, userData); return polygonBody; }
public PlayerSelect(int mode) { world = new World(Vector2.Zero); backPressed = true; confirmPressed = true; upPressed = true; downPressed = true; showButton = false; this.Mode = mode; boxes = new List<PlayerSelectBox>(); boxes.Add(new PlayerSelectBox(new Vector2(270, 145), PlayerIndex.One, 0)); boxes.Add(new PlayerSelectBox(new Vector2(770, 145), PlayerIndex.Two, 1)); boxes.Add(new PlayerSelectBox(new Vector2(270, 550), PlayerIndex.Three, 2)); boxes.Add(new PlayerSelectBox(new Vector2(770, 550), PlayerIndex.Four, 3)); components = new List<Component>(); if (mode == 0) { components.Add(new CheckBox(new Vector2(1400, 300), "Free For All", "0")); components.Add(new CheckBox(new Vector2(1400, 360), "Team Deathmatch", "1")); components.Add(new CheckBox(new Vector2(1400, 420), "1 Vs All", "2")); ((CheckBox)components[0]).Checked = true; } components.Add(new Button(new Vector2(1500, 600), MainGame.tex_ps_next, "next")); }
public PathTile(List<Vector2> localPoints, Vector2 position, World world, bool MakroCollision = false) { body = new Body(world); body.Position = ConvertUnits.ToSimUnits(position); body.UserData = "Wall"; body.IsStatic = true; Vertices terrain = new Vertices(); foreach (Vector2 point in localPoints) { terrain.Add(ConvertUnits.ToSimUnits(point)); } for (int i = 0; i < terrain.Count - 1; ++i) { FixtureFactory.AttachEdge(terrain[i], terrain[i + 1], body); body.FixtureList[i].UserData = "Wall"; } body.Restitution = 0f; body.Friction = float.MaxValue; if (!MakroCollision) body.CollisionCategories = Category.Cat15 & ~Category.Cat3; else body.CollidesWith = Category.Cat29; }
public TetrisPlayer(Game game, World world) : base(game) { _world = world; tetrisShapes.Add(new bool[,] { { true, false }, { true, false }, { true, true } }); tetrisShapes.Add(new bool[,] { { true, true, true }, { false, false, true } }); tetrisShapes.Add(new bool[,] { { true, true }, { true, true } }); tetrisShapes.Add(new bool[,] { { true, true, true }, { false, true, false } }); tetrisShapes.Add(new bool[,] { { true }, { true }, { true }, { true } }); tetrisShapes.Add(new bool[,] { { false, true, true }, { true, true, false } }); tetrisShapes.Add(new bool[,] { { true, true, false }, { false, true, true } }); tetrisShapes.Add(new bool[,] { { true } }); tetrisShapes.Add(new bool[,] { { true }, { true } }); tetrisShapes.Add(new bool[,] { { true }, { true }, { true } }); tetrisProb.Add(1); // LL tetrisProb.Add(1); // LR tetrisProb.Add(4); // O tetrisProb.Add(2); // T tetrisProb.Add(4); // I tetrisProb.Add(1); // Z tetrisProb.Add(1); // MZ tetrisProb.Add(1); // I1 tetrisProb.Add(1); // I2 tetrisProb.Add(3); // I3 Game1.Timers.Create(SPAWN_TIME, false, Spawn); }
public Border(World _world) { _anchorBottom = BodyFactory.CreateLineArc(_world, 2* MathHelper.Pi, 100, 100, position: new Vector2 (40f, 36f)); _anchorTop = BodyFactory.CreateLineArc(_world, MathHelper.Pi, 100, 100, position: new Vector2(40f, 36f), rotation: MathHelper.Pi); _exitBottom = BodyFactory.CreateLineArc(_world, 2 * MathHelper.Pi, 100, 110, position: new Vector2(40f, 36f)); _exitTop = BodyFactory.CreateLineArc(_world, MathHelper.Pi, 100, 110, position: new Vector2(40f, 36f), rotation: MathHelper.Pi); _exitTop.OnCollision += OnCollision; _exitBottom.OnCollision += OnCollision; _exitTop.CollisionCategories = Category.All; _exitTop.CollidesWith = Category.All; _exitBottom.CollisionCategories = Category.All; _exitBottom.CollidesWith = Category.All; _anchorTop.CollisionCategories = Category.Cat5; //.All & ~Category.Cat3 & ~Category.Cat2; _anchorTop.CollidesWith = Category.Cat1;//Category.All & ~Category.Cat3 & ~Category.Cat2; //collides with enemy and player _anchorBottom.CollisionCategories = Category.All & ~Category.Cat3; _anchorBottom.CollidesWith = Category.Cat1;//Category.All & ~Category.Cat3 & ~Category.Cat2; //collides with enemy and player //_anchorTop.IsSensor = true; //_anchorTop.ContactList //_anchorBottom.OnSeparation += OnSeparation; //System.Diagnostics.Debug.WriteLine( _anchorTop.ContactList+"contact list"); }
public static void Deserialize(World world, string filename) { using (FileStream fs = new FileStream(filename, FileMode.Open)) { new WorldXmlDeserializer().Deserialize(world, fs); } }
// Constructor public LinearMovingPlatform(World world, Vector2 initialPosition, Vector2 finalPosition, float nearTargetPositionDistance, float width, float speed, bool reverse) : base(world, initialPosition, finalPosition, width, speed) { Vector2 startPosition; if (!reverse) { movingTowardFinal = true; startPosition = initialPosition; } else { movingTowardFinal = false; startPosition = finalPosition; } SetUpPlatformTile(startPosition); this.nearTargetPositionDistance = ConvertUnits.ToSimUnits(nearTargetPositionDistance); // calculate the maximum velocity // it depends on the angle between the initial and final position Vector2 displacementFromFinalToInitial = new Vector2(finalPosition.X - initialPosition.X, finalPosition.Y - initialPosition.Y); if (displacementFromFinalToInitial.X <= 0) { maxVelocity = new Vector2(0, speed); } else if (displacementFromFinalToInitial.Y <= 0) { maxVelocity = new Vector2(speed, 0); } else { double angle = Math.Atan2(displacementFromFinalToInitial.X, displacementFromFinalToInitial.Y); maxVelocity = new Vector2(speed * (float)Math.Sin(angle), speed * (float)Math.Cos(angle)); } }
public void LoadContent(World world, Vector2 size, Vector2 position, ContentManager Content, string texturePath, DirectionEnum direction, float speed) { //Initialisation du body body = BodyFactory.CreateRectangle(world, size.X, size.Y, 1f); body.FixtureList[0].UserData = (int)(1000+id); body.BodyType = BodyType.Dynamic; body.Position = position; this.bodySize = size; body.FixtureList[0].IsSensor = true; //Initialisation de l'image du block Vector2 imagePosition = new Vector2(ConvertUnits.ToDisplayUnits(position.X), ConvertUnits.ToDisplayUnits(position.Y)); image = new Image(); image.LoadContent(Content, texturePath, Color.White, imagePosition); image.ScaleToMeters(size); if (direction == DirectionEnum.LEFT) { this.speedDirection = new Vector2(-1,0); } else { this.speedDirection = new Vector2(1, 0); } this.direction = direction; this.speed = speed; }
public PhysicsScene() { world = null; camera = new Camera(); player = new Player(); collectibleItems = new List<CollectibleItem>(); enemies = new List<Enemy>(); map = new Map(""); dynMap = new DynamicMap(""); mapBack = new MapBackground(""); projectiles = new List<Projectile>(); projectileFactory = new ProjectileFactory(); lifeBarFrame = new Image(); lifeBar = new Image(); projectileBarFrame = new Image(); projectileBar = new Image(); }
public override void LoadContent(FarseerPhysics.Dynamics.World aWorld, Microsoft.Xna.Framework.Graphics.Texture2D aTexture) { theBody = BodyFactory.CreateCircle(aWorld, (float)ConvertUnits.ToSimUnits((aTexture.Width / 2) - 2), 1.0f); objectTexture = aTexture; theBody.BodyType = BodyType.Dynamic; theBody.Restitution = 0.5f; }
/// <summary> /// Initializes a new instance of the <see cref="Platform"/> class. /// </summary> /// <param name="description">The platform description.</param> /// <param name="physicsWorld">The physics world.</param> /// <param name="spriteBatch">The sprite batch to use for rendering.</param> /// <param name="contentManager">The game's content manager.</param> public Platform(PlatformDescription description, ref World physicsWorld, SpriteBatch spriteBatch, ContentManager contentManager) { this.spriteOffsets = new List<Vector2>(); this.sprite = new Sprite(); this.InitializeAndLoadSprites(spriteBatch, contentManager, description); this.SetUpPhysics(ref physicsWorld, description); }
public PhysicsObject(World world, Vector2 position, Texture2D texture, Vector2 size, float mass) { this.Size = size; this.texture = texture; SetUpPhysics(world, position, mass); }
public PhysicsGameEntity(Game game, World world, Category collisionCategory, Body body, Vector2 origin) : this(game,world,collisionCategory) { Body = body; Center = origin; Body.CollisionCategories = collisionCategory; }
public AIKnight(World world) : base(world) { BaseAttribute[UnitAttribute.Speed] = 3f; Body.Friction = 0f; Color = Color.Gray; }
/// <summary> /// Constructs a FPE Body from the given list of vertices and density /// </summary> /// <param name="game"></param> /// <param name="world"></param> /// <param name="vertices">The collection of vertices in display units (pixels)</param> /// <param name="bodyType"></param> /// <param name="density"></param> public PhysicsGameEntity(Game game, World world, Category collisionCategory, Vertices vertices, BodyType bodyType, float density) : this(game,world,collisionCategory) { ConstructFromVertices(world,vertices,density); Body.BodyType = bodyType; Body.CollisionCategories = collisionCategory; }
/// <summary> /// Creates the bonuses, obstacles and power ups contained in a level. /// </summary> /// <param name="interactiveEntityDescriptions">A list of interactive entity descriptions.</param> /// <param name="physicsWorld">The physics world to create the entities in.</param> /// <param name="interactiveEntities">An empty list to store the interactive entities in.</param> /// <param name="mineCart">The mine cart entity.</param> /// <param name="cartSwitch">The switch entity.</param> /// <param name="spriteBatch">The sprite batch to use for rendering.</param> /// <param name="contentManager">The game's content manager.</param> public static void CreateInteractiveEntities(List<InteractiveEntityDescription> interactiveEntityDescriptions, ref World physicsWorld, ref List<InteractiveEntity> interactiveEntities, ref MineCart mineCart, ref Switch cartSwitch, SpriteBatch spriteBatch, ContentManager contentManager) { if (interactiveEntities.Count == 0) { foreach (InteractiveEntityDescription description in interactiveEntityDescriptions) { if (EntityConstants.PowerUpNames.Contains(description.Name)) { interactiveEntities.Add(new PowerUp(ref physicsWorld, spriteBatch, contentManager, description, EntitySettingsLoader.GetPowerUpSettings(description.Name))); } else if (EntityConstants.BonusNames.Contains(description.Name) || EntityConstants.ObstacleNames.Contains(description.Name)) { interactiveEntities.Add(new BonusOrObstacle(ref physicsWorld, spriteBatch, contentManager, description, EntitySettingsLoader.GetObstacleOrBonusSetting(description.Name))); } else if (description.Name == EntityConstants.CartBody) { mineCart = new MineCart(spriteBatch, contentManager, ref physicsWorld, description.Position, 100.0f, 240.0f, 350.0f, 80.0f, -80.0f); } else if (description.Name == EntityConstants.Switch) { cartSwitch = new Switch(spriteBatch, contentManager, ref physicsWorld, description.Position, mineCart); } } } }
public static Body createPolygon( World world, Vertices vertices, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static, object userData = null ) { for( var i = 0; i < vertices.Count; i++ ) vertices[i] *= FSConvert.displayToSim; return FarseerPhysics.Factories.BodyFactory.CreatePolygon( world, vertices, density, FSConvert.toSimUnits( position ), rotation, bodyType, userData ); }
public Wall(World world, WallCompiled wall) { if (wall.Shape == ShapeData.Closed) Fixtures = new Fixture[wall.Verts1.Length]; else Fixtures = new Fixture[wall.Verts1.Length-1]; for (int i = 0; i < wall.Verts1.Length-1; i++) addQuad(world, wall, i, i+1); if (wall.Shape == ShapeData.Closed) addQuad(world, wall, wall.Verts1.Length-1, 0); }
public static Body createLoopShape( World world, Vertices vertices, Vector2 position = new Vector2(), object userData = null ) { for( var i = 0; i < vertices.Count; i++ ) vertices[i] *= FSConvert.displayToSim; return FarseerPhysics.Factories.BodyFactory.CreateLoopShape( world, vertices, FSConvert.toSimUnits( position ), userData ); }
public static void Serialize(World world, string filename) { using (FileStream fs = new FileStream(filename, FileMode.Create)) { new WorldXmlSerializer().Serialize(world, fs); } }
public Player(World world, float x, float y, Texture2D texture) { torso = BodyFactory.CreateRectangle(world, 60 * MainGame.PIXEL_TO_METER, 80 * MainGame.PIXEL_TO_METER, 1); torso.Position = new Vector2(x * MainGame.PIXEL_TO_METER, y * MainGame.PIXEL_TO_METER); torso.BodyType = BodyType.Dynamic; torso.UserData = this; legs = BodyFactory.CreateCircle(world, 31 * MainGame.PIXEL_TO_METER, 1); legs.Position = torso.Position + new Vector2(0, 40 * MainGame.PIXEL_TO_METER); legs.BodyType = BodyType.Dynamic; legs.Friction = 5.0f; legs.UserData = this; JointFactory.CreateFixedAngleJoint(world, torso); axis = JointFactory.CreateRevoluteJoint(world, torso, legs, Vector2.Zero); axis.CollideConnected = false; axis.MotorEnabled = true; axis.MotorSpeed = 0.0f; axis.MotorTorque = 3.0f; axis.MaxMotorTorque = 10.0f; onGround = false; facingLeft = false; jumpForce = new Vector2(0, -1f); rightAirForce = new Vector2(5f, 0); leftAirForce = -1 * rightAirForce; prevVelocity = Vector2.Zero; normal = Vector2.Zero; pressW = false; holdW = false; texIdle = new AnimatedTexture(texture, 24, 0, 0, 120, 140); texRun = new AnimatedTexture(texture, 19, 0, 140, 120, 140); texJump = new AnimatedTexture(texture, 9, 19 * 120, 140, 120, 140, 1, false, false); currentTexture = texIdle; }
public GameCharacter(Game game, World world, Vector2 position, Vector2 size, SpriteAnimation animation, BodyType bodyType) : base(game, world, position, size, animation, bodyType) { // Don't allow characters to rotate this.body.FixedRotation = true; this.jumpState = 0; }
public PinballMiniGame(GraphicsDevice graphicsDevice) { this.graphicsDevice = graphicsDevice; sb = new SpriteBatch(graphicsDevice); ein = new Kinect(0, 0); ein.Init(); circleTexture = CreateCircle(ball_radius, graphicsDevice); gameState = MiniGameState.Initialized; physicsWorld = new World(new Vector2(0, .982f)); paddleSize = new Vector2(300, 16); paddleLeft = BodyFactory.CreateRectangle(physicsWorld, paddleSize.X * 2 * pixelToUnit, paddleSize.Y * pixelToUnit, 1000f); paddleLeft.BodyType = BodyType.Dynamic; paddleLeft.Position = new Vector2(8 * pixelToUnit, (GameConstants.MiniGameCanvasHeight - 100) * pixelToUnit); paddleLeft.LocalCenter = new Vector2(0, 0); paddleLeft.SleepingAllowed = false; paddleLeft.Restitution = 1.0f; paddleLeft.IgnoreGravity = true; ball = BodyFactory.CreateCircle(physicsWorld, (ball_radius) * pixelToUnit, 1000f); ball.BodyType = BodyType.Dynamic; ball.Position = new Vector2(100 * pixelToUnit, 100 * pixelToUnit); ball.Restitution = 1.0f; ball.SleepingAllowed = false; }
/// <summary> /// Initializes a new instance of the <see cref="PowerUp"/> class. /// </summary> /// <param name="physicsWorld">The physics world.</param> /// <param name="spriteBatch">The sprite batch to use for rendering.</param> /// <param name="contentManager">The game's content manager.</param> /// <param name="description">The entity description.</param> /// <param name="settings">The power up settings.</param> public PowerUp(ref World physicsWorld, SpriteBatch spriteBatch, ContentManager contentManager, InteractiveEntityDescription description, PowerUpSetting settings) : base(ref physicsWorld, description) { this.name = settings.Name; this.timeOfEffect = settings.TimeOfEffect; switch (this.name) { case EntityConstants.InvincibleName: this.type = PowerUpType.Invincibility; break; case EntityConstants.HealthName: this.type = PowerUpType.Health; break; case EntityConstants.JumpName: this.type = PowerUpType.Jump; break; case EntityConstants.SpeedName: this.type = PowerUpType.Speed; break; default: this.type = PowerUpType.None; break; } this.PhysicsBody.UserData = new InteractiveEntityUserData(InteractiveEntityType.PowerUp, this.timeOfEffect, this.type); this.InitializeAndLoad(spriteBatch, contentManager); }
public override void LoadContent(FarseerPhysics.Dynamics.World aWorld, Microsoft.Xna.Framework.Graphics.Texture2D aTexture) { theBody = BodyFactory.CreateRectangle(aWorld, (float)ConvertUnits.ToSimUnits(aTexture.Width - 2), (float)ConvertUnits.ToSimUnits(aTexture.Height - 2), 1.0f); objectTexture = aTexture; theBody.BodyType = BodyType.Static; theBody.Restitution = 0.3f; theBody.Friction = 1.0f; }
/// <summary> /// This essentially clears all objects from the world. /// Used when moving from one room to another, /// when we switch out all objects for new ones. /// </summary> // OPT: Someday might be a good idea to just empty data structures instead of // freeing and re-allocating them. public void ClearWorld() { // BUGGO: This should use a real resolution. RenderManager = new RenderManager(1024, 768); PhysicsWorld = new FarseerPhysics.Dynamics.World(Util.Gravity); Actors = new HashSet <Actor>(); ActorsToAdd = new List <Actor>(); ActorsToRemove = new List <Actor>(); }
public override void Init(FarseerPhysics.Dynamics.World w, Kinect.RagdollManager r) { world = w; target = r.ragdoll; body.setWorld(w); body.OnCollision += new OnCollisionEventHandler(body_OnCollision); world.ProcessChanges(); IsOperational = true; }
public Body(FarseerPhysics.Dynamics.World farseerWorld, GameObject gameObject) { this._farseerWorld = farseerWorld; this._body = new FarseerPhysics.Dynamics.Body( this._farseerWorld, Vector2.Zero, 0f, IsRigid ? BodyType.Dynamic : BodyType.Static, gameObject ); }
public CollisionSystem() #endif : base( SystemOrders.Update.Physics, new int[] { ComponentTypeIds.Placement, ComponentTypeIds.Physics }, new uint[] { Messages.SetVelocity } ) { FarseerPhysics.Settings.UseFPECollisionCategories = true; physicsWorld = new FarseerPhysics.Dynamics.World(Vector2.Zero, new FarseerPhysics.Collision.AABB(Vector2.Zero, new Vector2(20))); collisionBodyPool = new CollisionBodyPool(physicsWorld); #if DEBUG this.device = device; this.content = content; this.camera = camera; #endif }
public Box2DWorld() { _world = new FarseerPhysics.Dynamics.World(new Microsoft.Xna.Framework.Vector2(0)); _queryCallbackDelegate = QueryCallback; }
public void Dispose() { _world = null; }
public PlayerBodyGenerator(FarseerPhysics.Dynamics.World physicsWorld, DefaultEcs.World world) : base(physicsWorld, world) { }
public override void Initialize() { PhysicsWorld = new FarseerPhysics.Dynamics.World(new Vector2(0f, 0 * -9.82f)); }
public Body(World world) : this(world, null) { }
public ConstructBodyGenerator(FarseerPhysics.Dynamics.World physicsWorld, DefaultEcs.World world) : base(physicsWorld, world) { }
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)); }
/// <summary> /// Generates collision geometry based on map layer and adds it to the world. /// </summary> /// <param name="mapConfig">Config file for map used</param> public void GenerateMapCollidersFromFile(MapConfig mapConfig) { var inBodyData = new Dictionary <string, List <Vertices> >(); // Tranlate vertex file into Dictionary of verticies // #region Translate vertex file into 'inBodyData' var vertexFilePth = mapConfig.VertexFile; #if PSM vertexFilePth = vertexFilePth.Insert(0, @"Application\"); #endif var vertexReader = new StreamReader(vertexFilePth); // Read: Number of colliders. var colliderCout = Convert.ToInt32(vertexReader.ReadLine()); for (var i = 0; i < colliderCout; i++) { // Read: Collider key. var colliderKey = vertexReader.ReadLine(); if (colliderKey == null) { throw new Exception("Error when reading collider key."); } inBodyData[colliderKey] = new List <Vertices>(); // Read: Number of convex bodies. var convexBodyCount = Convert.ToInt32(vertexReader.ReadLine()); for (var j = 0; j < convexBodyCount; j++) { // Add new convex body. inBodyData[colliderKey].Add(new Vertices()); // Read: Number of verticies in convex body. var vertexCount = Convert.ToInt32(vertexReader.ReadLine()); for (var k = 0; k < vertexCount; k++) { // Read: Vertex data. string test = vertexReader.ReadLine(); var x = Convert.ToDouble(test); var y = Convert.ToDouble(vertexReader.ReadLine()); // Add vertex data. inBodyData[colliderKey].Last().Add(new Vector2((float)x, (float)y)); } } } #endregion Translate vertex file into 'inBodyData' var tileTypesUsed = new List <string>(); var tilePlacement = new Dictionary <Vector2, string>(); // Translate raw map file into tile placement information // #region Translate raw map file into 'tileTypesUsed' and 'tilePlacement' var rawMapPath = mapConfig.MapDirectory; rawMapPath = rawMapPath.Insert(0, @"Content\"); #if PSM rawMapPath = rawMapPath.Insert(0, @"Application\"); #endif rawMapPath += ".tide"; var mapReader = XmlReader.Create(rawMapPath); string tileSheetId = ""; string tileSheetKey = ""; var tileIndex = new Vector2(-1, -1); var tileSize = Size.Zero; bool collisionLayer = false; // Read in raw map file while (mapReader.Read()) { // Initialize collision layer. if (mapReader.Name == "Layer") { if (mapReader.NodeType != XmlNodeType.EndElement) { if (mapConfig.CollisionLayers.Contains(mapReader.GetAttribute("Id"))) { tileIndex = new Vector2(-1, -1); collisionLayer = true; } else { collisionLayer = false; } } } // Process collision layer if (collisionLayer) { // Record tile size. if (mapReader.Name == "Dimensions") { tileSize = Size.FromString(mapReader.GetAttribute("TileSize")); } // Record tile sheet name. if (mapReader.Name == "TileSheet") { tileSheetId = mapReader.GetAttribute("Ref"); } // Process tile indexes on new row. if (mapReader.Name == "Row") { if (mapReader.NodeType != XmlNodeType.EndElement) { tileIndex.Y += 1; tileIndex.X = -1; } } // Read information for each tiles location. if (mapReader.Name == "Static") { tileIndex.X += 1; // Generate key for tile. tileSheetKey = tileSheetId + mapReader.GetAttribute("Index"); // Add key to list if not already contained. if (!tileTypesUsed.Contains(tileSheetKey)) { tileTypesUsed.Add(tileSheetKey); } // Recored tile placement for tile. tilePlacement[new Vector2(tileIndex.X * tileSize.Width, tileIndex.Y * tileSize.Height)] = tileSheetKey; } // Skip unassigned tiles. if (mapReader.Name == "Null") { tileIndex.X += Convert.ToInt32(mapReader.GetAttribute("Count")); } } } #endregion Translate raw map file into 'tileTypesUsed' and 'tilePlacement' // Tranlate tile types into temporary physics bodies // #region Populate physics world with map colliders var tileColliderTypes = new Dictionary <string, Body>(); var tempWorld = new FarseerPhysics.Dynamics.World(Vector2.Zero); foreach (var tileUsed in tileTypesUsed) { tileColliderTypes[tileUsed] = BodyFactory.CreateCompoundPolygon(tempWorld, inBodyData[tileUsed], 1, Vector2.Zero); } // Copy physics bodies into physical world at tile locations // foreach (var colliderPair in tilePlacement) { _staticMapColliders.Add(tileColliderTypes[colliderPair.Value].DeepClone(World)); _staticMapColliders.Last().Position = ConvertUnits.ToSimUnits(colliderPair.Key - Camera.ScreenCenter); } #endregion Populate physics world with map colliders }
/// <summary> /// AddToWorld() and RemoveFromWorld() are necessary to make a square peg fit in a round hole, essentially. /// See, we're going to want to have actors with Body's attached to them that aren't in the current World. /// For instance, when they're representing a room that hasn't been entered yet. /// Or when they've just been loaded and we're about to create them but still need to know where the heck /// they are. /// Since Farseer makes it impossible to have a Body that doesn't have a World attached to it, we make a dummy /// World and use that to initialize Body's, then replace it with a copy that refers to the real game's World /// when the actor goes live. /// OPT: This allocates, irritatingly, but won't be happening every frame. /// </summary> /// <param name="world">World.</param> public void AddToWorld(Dyn.World world) { PBody = PBody.Clone(world: world); Fixture = PBody.CreateFixture(Shape); Log.Message("Added body to world, type {0}, actor {1}", PBody.BodyType, Owner); }
public void RemoveFromWorld(Dyn.World world) { world.RemoveBody(PBody); PBody = PBody.Clone(world: DummyWorld); }
public PhysicalWorld() { this._farseerWorld = new FarseerPhysics.Dynamics.World(Microsoft.Xna.Framework.Vector2.Zero); }
public virtual void Load(FarseerPhysics.Dynamics.World world) { }