public BasePlayer(IPlayerSettings playerSettings, IPhysicsComponent physicsComponent, IBoundaryCollider boundaryCollider, IWeapons weapons, ITimer timer) { this.PlayerSettings = playerSettings; this.PlayerScore = new PlayerScore(); if (physicsComponent == null) this.PhysicsComponent = new DummyPhysicsComponent(); else this.PhysicsComponent = physicsComponent; this.PhysicsComponent.CollidedWithWorld += () => InContactWithLevel = true; this.PhysicsComponent.WasShot += Damage; this.Weapons = weapons; this.Weapons.DamagedAPlayer += (damage, physicsComp) => physicsComp.OnWasShot(this, damage); this.Timer = timer; this.BoundaryCollider = boundaryCollider; this.Health = BasePlayer.StartHealth; this.Status = PlayerStatus.Alive; this.Position = new Vector2(400, 100); this.PhysicsComponent.CollisionGroup = BasePlayer.CollisionGroup; }
private bool IsAroundCollider(ITransformComponent transform, IMoverComponent mover, IPhysicsComponent collider) { foreach (var entity in _entityManager.GetEntitiesInRange(transform.Owner, mover.GrabRange, true)) { if (entity == transform.Owner) { continue; // Don't try to push off of yourself! } if (!entity.TryGetComponent <IPhysicsComponent>(out var otherCollider)) { continue; } // Don't count pulled entities if (otherCollider.HasController <PullController>()) { continue; } // TODO: Item check. var touching = ((collider.CollisionMask & otherCollider.CollisionLayer) != 0x0 || (otherCollider.CollisionMask & collider.CollisionLayer) != 0x0) && // Ensure collision !entity.HasComponent <IItemComponent>(); // This can't be an item if (touching) { return(true); } } return(false); }
public override void Reallocate() { renderComponent = null; physicsComponent = null; base.Reallocate(); }
private void UpdatePosition(IPhysicsComponent physics, float frameTime) { var ent = physics.Entity; if (!physics.CanMove() || (physics.LinearVelocity.LengthSquared < Epsilon && MathF.Abs(physics.AngularVelocity) < Epsilon)) { return; } if (physics.LinearVelocity != Vector2.Zero) { if (ContainerHelpers.IsInContainer(ent)) { var relayEntityMoveMessage = new RelayMovementEntityMessage(ent); ent.Transform.Parent !.Owner.SendMessage(ent.Transform, relayEntityMoveMessage); // This prevents redundant messages from being sent if solveIterations > 1 and also simulates the entity "colliding" against the locker door when it opens. physics.LinearVelocity = Vector2.Zero; } } physics.Owner.Transform.DeferUpdates = true; _deferredUpdates.Add(physics); // Slow zone up in here if (physics.LinearVelocity.Length > _speedLimit) { physics.LinearVelocity = physics.LinearVelocity.Normalized * _speedLimit; } physics.WorldRotation += physics.AngularVelocity * frameTime; physics.WorldPosition += physics.LinearVelocity * frameTime; }
public override void Initialize() { renderComponent = Parent.GetComponent <IRenderComponent>(); physicsComponent = Parent.GetComponent <IPhysicsComponent>(); base.Initialize(); }
public Manifold(IPhysicsComponent a, IPhysicsComponent b, bool hard) { A = a; B = b; Normal = PhysicsManager.CalculateNormal(a, b); Hard = hard; }
private void ProcessFriction(IPhysicsComponent body, float deltaTime) { if (body.LinearVelocity == Vector2.Zero) { return; } // sliding friction coefficient, and current gravity at current location var(friction, gravity) = GetFriction(body); // friction between the two objects var effectiveFriction = friction * body.Friction; // current acceleration due to friction var fAcceleration = effectiveFriction * gravity; // integrate acceleration var fVelocity = fAcceleration * deltaTime; // Clamp friction because friction can't make you accelerate backwards friction = Math.Min(fVelocity, body.LinearVelocity.Length); if (friction == 0.0f) { return; } // No multiplication/division by mass here since that would be redundant. var frictionVelocityChange = body.LinearVelocity.Normalized * -friction; body.LinearVelocity += frictionVelocityChange; }
public PhysicsComponent(IPhysicsComponent entity) : this() { _entity = entity; PhysicsEngine.Instance.AddComponent(_entity); _pos = ZeroPoint2D(); }
public PhysicsComponent(IPhysicsComponent entity, Point2D pos) : this() { _entity = entity; PhysicsEngine.Instance.AddComponent(_entity); _pos = pos; }
public override void Initialize() { renderComponent = Parent.GetComponent<IRenderComponent>(); physicsComponent = Parent.GetComponent<IPhysicsComponent>(); base.Initialize(); }
public PhysicsComponent(IPhysicsComponent entity, Point2D pos) : this() { _entity = entity; Artillery3R.Services.PhysicsEngine.AddComponent(_entity); _pos = pos; }
/// <summary> /// Call if this entity is relevant for the pathfinder /// </summary> /// <param name="entity"></param> /// TODO: These 2 methods currently don't account for a bunch of changes (e.g. airlock unpowered, wrenching, etc.) /// TODO: Could probably optimise this slightly more. public void AddEntity(IEntity entity, IPhysicsComponent physicsComponent) { // If we're a door if (entity.HasComponent <AirlockComponent>() || entity.HasComponent <ServerDoorComponent>()) { // If we need access to traverse this then add to readers, otherwise no point adding it (except for maybe tile costs in future) // TODO: Check for powered I think (also need an event for when it's depowered // AccessReader calls this whenever opening / closing but it can seem to get called multiple times // Which may or may not be intended? if (entity.TryGetComponent(out AccessReader accessReader) && !_accessReaders.ContainsKey(entity)) { _accessReaders.Add(entity, accessReader); ParentChunk.Dirty(); } return; } DebugTools.Assert((PathfindingSystem.TrackedCollisionLayers & physicsComponent.CollisionLayer) != 0); if (!physicsComponent.Anchored) { _physicsLayers.Add(entity, physicsComponent.CollisionLayer); } else { _blockedCollidables.Add(entity, physicsComponent.CollisionLayer); GenerateMask(); ParentChunk.Dirty(); } }
public Character(string name) : base(name) { _physicsComponent = new PhysicsComponent(this); _damageComponent = new DamageableComponent(this); _stateComponent = new StateComponent <ChararacterState>(ChararacterState.Idle); DrawableComponent = new DrawableComponent(this); }
public LevelPiece(IPhysicsComponent physicsComponent) { _physicsComponent = physicsComponent; _physicsComponent.IsStatic = true; Random rnd = new Random((int)(physicsComponent.Size.X + physicsComponent.Size.Y)); Color = new Color((float)rnd.NextDouble(), (float)rnd.NextDouble(), (float)rnd.NextDouble()); }
public void SetUp() { stubPlayerSettings = MockRepository.GenerateStub<IPlayerSettings>(); stubPhysicsComponent = MockRepository.GenerateStub<IPhysicsComponent>(); stubBoundaryCollider = MockRepository.GenerateStub<IBoundaryCollider>(); stubWeapons = MockRepository.GenerateStub<IWeapons>(); stubTimer = MockRepository.GenerateStub<ITimer>(); player = new BasePlayer(stubPlayerSettings, stubPhysicsComponent, stubBoundaryCollider, stubWeapons, stubTimer); }
private EntityType(short id, IInputComponent input, IGraphicsComponent graphics, IPhysicsComponent physics) { Id = id; Input = input; Graphics = graphics; Physics = physics; }
public static bool IsRelevant(IEntity entity, IPhysicsComponent physicsComponent) { if (entity.Transform.GridID == GridId.Invalid || (PathfindingSystem.TrackedCollisionLayers & physicsComponent.CollisionLayer) == 0) { return(false); } return(true); }
private void UpdatePosition(IPhysicsComponent physics, float frameTime) { var ent = physics.Entity; if (!physics.CanMove() || (physics.LinearVelocity.LengthSquared < Epsilon && MathF.Abs(physics.AngularVelocity) < Epsilon)) { return; } if (physics.LinearVelocity != Vector2.Zero) { if (ContainerHelpers.IsInContainer(ent)) { var relayEntityMoveMessage = new RelayMovementEntityMessage(ent); ent.Transform.Parent !.Owner.SendMessage(ent.Transform, relayEntityMoveMessage); // This prevents redundant messages from being sent if solveIterations > 1 and also simulates the entity "colliding" against the locker door when it opens. physics.LinearVelocity = Vector2.Zero; } } physics.Owner.Transform.DeferUpdates = true; _deferredUpdates.Add(physics); // Slow zone up in here if (physics.LinearVelocity.Length > _speedLimit) { physics.LinearVelocity = physics.LinearVelocity.Normalized * _speedLimit; } var newPosition = physics.WorldPosition + physics.LinearVelocity * frameTime; var owner = physics.Owner; var transform = owner.Transform; // Change parent if necessary if (!ContainerHelpers.IsInContainer(owner)) { // This shoouullddnnn'''tt de-parent anything in a container because none of that should have physics applied to it. if (_mapManager.TryFindGridAt(owner.Transform.MapID, newPosition, out var grid) && grid.GridEntityId.IsValid() && grid.GridEntityId != owner.Uid) { if (grid.GridEntityId != transform.ParentUid) { transform.AttachParent(owner.EntityManager.GetEntity(grid.GridEntityId)); } } else { transform.AttachParent(_mapManager.GetMapEntity(transform.MapID)); } } physics.WorldRotation += physics.AngularVelocity * frameTime; physics.WorldPosition = newPosition; }
/// <summary> /// Constructor. /// </summary> /// <param name="root">Root object to which the entity belongs.</param> /// <param name="name">Name of the entity.</param> public PhysicsPlane(Root root, string name) : base(root, name) { ISpatialComponent spatial = ComponentFactory.createSpatialComponent(this.Root, "spatial"); IPhysicsComponent physics = ComponentFactory.createPhysicsComponent(this.Root, "physicsComponent"); physics.BuildCollisionPlane(new Vector3(0.0f, 1.0f, 0.0f), 0.0f); physics.Immovable = true; AddComponent(spatial); AddComponent(physics); }
/// <summary> /// Constructor. /// </summary> /// <param name="root">Root object to which the entity belongs.</param> /// <param name="name">Name of the entity.</param> /// <param name="normal">Normal of the plane.</param> /// <param name="distance"> /// Distance along the normal to the plane. For instance, if the normal is (0,1,0), that /// is, the Y axis, the created plane will be y = distance. /// </param> public PhysicsPlane(Root root, string name, Vector3 normal, float distance) : base(root, name) { ISpatialComponent spatial = ComponentFactory.createSpatialComponent(this.Root, "spatial"); IPhysicsComponent physics = ComponentFactory.createPhysicsComponent(this.Root, "physicsComponent"); physics.BuildCollisionPlane(normal, distance); physics.Immovable = true; AddComponent(spatial); AddComponent(physics); }
public Rocket(Vector2 position, Vector2 direction, IPhysicsComponent physicsComponent) { this.PhysicsComponent = physicsComponent; this.IsAlive = true; this.PhysicsComponent.Size = Rocket.Size; this.PhysicsComponent.Position = position; this.PhysicsComponent.LinearVelocity = direction * Rocket.Speed; this.PhysicsComponent.CollidedWithWorld += () => this.IsAlive = false; }
/// <summary> /// PlayerJumpState constructor /// </summary> /// <param name="pAnimator"></param> /// <param name="pArgs"></param> public PlayerJumpState(int pEntityID, IAnimator pAnimator, IAudioPlayer pAudioPlayer, IKeyboardInput pArgs, IPhysicsComponent pPhysicsComponent) { _animator = pAnimator; _audioPlayer = pAudioPlayer; _args = pArgs; // INSTANTIATE _frameTime _frameTime = 0.009f; _entityUID = pEntityID; _ySpeed = 3; _physicsComponent = pPhysicsComponent; }
private (float friction, float gravity) GetFriction(IPhysicsComponent body) { if (!body.OnGround) { return(0f, 0f); } var location = body.Owner.Transform; var grid = _mapManager.GetGrid(location.Coordinates.GetGridId(EntityManager)); var tile = grid.GetTileRef(location.Coordinates); var tileDef = _tileDefinitionManager[tile.Tile.TypeId]; return(tileDef.Friction, grid.HasGravity ? 9.8f : 0f); }
public Projectile(string name, Weapon parentWeapon, Vector pos, Vector vel, float damage, float explRad, float damageRad) : base(name) { _parentWeapon = parentWeapon; _physicsComponent = new PhysicsComponent(this) { Pos = pos, Vel = vel }; _stateComponent = new StateComponent <ProjectileState>(ProjectileState.Alive); _baseDamage = damage; _explRad = explRad; _damageRad = damageRad; }
protected override void OnCollision(IPhysicsComponent physicsComponent, IPhysicsComponent colliding, Contact contact) { //Fire the damage action. var damageAction = Parent.ActionFactory.GetAction<BasicDamageAction>(); damageAction.Damage = damageComponent.Damage; var particleAction = Parent.ActionFactory.GetAction<EmitParticleAction>(); particleAction.ParticleName = "BallCollisionParticle"; particleAction.TargetPosition = ParentGameObject.Position; particleAction.Initialize(); var compositeAction = Parent.ActionFactory.GetAction<ParallelGameAction>(); compositeAction.AddAction(damageAction); compositeAction.AddAction(particleAction); Parent.FireAction(compositeAction, colliding.Parent); }
public static Dictionary<string, Body> DeserializeBodies(XElement element, IPhysicsManager physicsManager, IPhysicsComponent parent) { Dictionary<string, Body> bodies = new Dictionary<string, Body>(); IEnumerable<XElement> elements = element.Elements("body"); foreach (XElement bodyElement in elements) { Body body = DeserializeBody(bodyElement, physicsManager, parent); if (body != null) { string name = ((FarseerUserData) body.UserData).Name; bodies.Add(name, body); } } return bodies; }
/// <summary> /// Constructor for PlayerRunState /// </summary> public PlayerRunState(int pEntityID, IAnimator pAnimator, IAudioPlayer pAudioPlayer, IKeyboardInput pArgs, PassFloat pInvertTexture, IPhysicsComponent pPhysicsComponent) { // INSTANTIATE _animator _animator = pAnimator; // INSTANTIATE _audioPlayer _audioPlayer = pAudioPlayer; // INSTANTIATE _args _args = pArgs; // INSTANTIATE _frameTime _frameTime = 0.009f; _entityUID = pEntityID; // set _xSpeed _xSpeed = 7; // set _ySpeed _ySpeed = 35; // set facing direction _facingDirectionX = 1; _invertTexture = pInvertTexture; _physicsComponent = pPhysicsComponent; }
public void StartPull(IPhysicsComponent puller) { DebugTools.AssertNotNull(puller); if (_puller == puller) { return; } _puller = puller; if (ControlledComponent == null) { return; } ControlledComponent.WakeBody(); var message = new PullStartedMessage(this, _puller, ControlledComponent); _puller.Owner.SendMessage(null, message); ControlledComponent.Owner.SendMessage(null, message); }
/// <summary> /// Handles the collision detection. /// </summary> /// <param name="owner">The owner.</param> /// <param name="collidee">The collidee.</param> /// <returns></returns> protected bool HandleCollisionDetection(CollisionSkin owner, CollisionSkin collidee) { // If there are handlers for the CollisionDetected event we trigger it. We use the // Owner property of the PhysicsObject to obtain the IPhysicsComponent to which the body // belongs. From that we can get the entities that are colliding. if (CollisionDetected != null) { PhysicsBody body1 = owner.Owner as PhysicsBody; PhysicsBody body2 = collidee.Owner as PhysicsBody; if (body1 != null && body2 != null) { IPhysicsComponent component1 = body1.Owner; IPhysicsComponent component2 = body2.Owner; if (component1 != null && component2 != null) { CollisionDetected(component1.Owner, component2.Owner); } } } //We return true because we want the physics engine to handle the collision. return(true); }
public static Body DeserializeBody(XElement element, IPhysicsManager physicsManager, IPhysicsComponent parent) { Body body = null; FarseerUserData userData = new FarseerUserData(); //Read the shape used for this body. BodyType bodyType = BodyType.Static; if (element.Attribute("bodyType") != null) { if (element.Attribute("bodyType").Value.StartsWith("d", StringComparison.InvariantCultureIgnoreCase)) bodyType = BodyType.Dynamic; else if (element.Attribute("bodyType").Value.StartsWith("s", StringComparison.InvariantCultureIgnoreCase)) bodyType = BodyType.Static; else if (element.Attribute("bodyType").Value.StartsWith("k", StringComparison.InvariantCultureIgnoreCase)) bodyType = BodyType.Kinematic; } bool primary = false; if (element.Attribute("primary") != null) bool.TryParse(element.Attribute("primary").Value, out primary); Shape shape = null; XElement shapeElement = element.Element("shape"); if (shapeElement != null && shapeElement.Attribute("type") != null) { if (shapeElement.Attribute("type").Value.StartsWith("b", StringComparison.InvariantCultureIgnoreCase)) shape = DeserializeBoxShape(shapeElement); else if (shapeElement.Attribute("type").Value.StartsWith("c", StringComparison.InvariantCultureIgnoreCase)) shape = DeserializeCircleShape(shapeElement); else if (shapeElement.Attribute("type").Value.StartsWith("p", StringComparison.InvariantCultureIgnoreCase)) shape = DeserializePolygonShape(shapeElement); } if (shape != null) { string name; body = BodyFactory.CreateBody(physicsManager.PhysicsWorld); body.BodyType = bodyType; Vector2 offset = Vector2.Zero; float friction = 0.5f, linearDamping = 5f, restitution = 0f, mass = 1f; bool fixedRotation = false; if (element.Element("friction") != null) float.TryParse(element.Element("friction").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out friction); if (element.Element("linearDamping") != null) float.TryParse(element.Element("linearDamping").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out linearDamping); if (element.Element("restitution") != null) float.TryParse(element.Element("restitution").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out restitution); if (element.Element("mass") != null) float.TryParse(element.Element("mass").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out mass); if (element.Element("fixedRotation") != null) bool.TryParse(element.Element("fixedRotation").Value, out fixedRotation); if (element.Element("offset") != null) offset = offset.DeserializeOffset(element.Element("offset")); body.CreateFixture(shape); body.Friction = friction; body.LinearDamping = linearDamping; body.Restitution = restitution; body.Mass = mass; body.FixedRotation = fixedRotation; name = element.Attribute("name") != null ? element.Attribute("name").Value : body.BodyId.ToString(); userData.TopLeftOffset = ConvertUnits.GetTopLeftCorner(body.FixtureList[0], 0); userData.Name = name; userData.Primary = primary; userData.Owner = parent; userData.Offset = offset; body.UserData = userData; } return body; }
public LocalPlayer(IPlayerSettings playerSettings, IPhysicsComponent physicsComponent, IBoundaryCollider boundaryCollider, IWeapons weapons, ITimer timer) : base(playerSettings, physicsComponent, boundaryCollider, weapons, timer) { Console.Write("Creating Local Player"); }
protected void UpdateKinematics(ITransformComponent transform, IMoverComponent mover, IPhysicsComponent physics) { physics.EnsureController <MoverController>(); var weightless = transform.Owner.IsWeightless(); if (weightless) { // No gravity: is our entity touching anything? var touching = IsAroundCollider(transform, mover, physics); if (!touching) { transform.LocalRotation = physics.LinearVelocity.GetDir().ToAngle(); return; } } // TODO: movement check. var(walkDir, sprintDir) = mover.VelocityDir; var combined = walkDir + sprintDir; if (combined.LengthSquared < 0.001 || !ActionBlockerSystem.CanMove(mover.Owner) && !weightless) { if (physics.TryGetController(out MoverController controller)) { controller.StopMoving(); } } else { if (weightless) { if (physics.TryGetController(out MoverController controller)) { controller.Push(combined, mover.CurrentPushSpeed); } transform.LocalRotation = physics.LinearVelocity.GetDir().ToAngle(); return; } var total = walkDir * mover.CurrentWalkSpeed + sprintDir * mover.CurrentSprintSpeed; { if (physics.TryGetController(out MoverController controller)) { controller.Move(total, 1); } } transform.LocalRotation = total.GetDir().ToAngle(); HandleFootsteps(mover); } }
public virtual void SetPhysicsComponent(IPhysicsComponent pPhysicsComponent) { _physicsComponent = pPhysicsComponent; }
public override void Initialize() { ballPhysics = ParentGameObject.GetComponent<IPhysicsComponent>(); base.Initialize(); }
public const float SMOOTHING_FACTOR = 0.8f; // 1f tries to catch up completely between each tick and is likely to be unstable public NetworkPlayer(IPlayerSettings playerSettings, IPhysicsComponent physicsComponent, IWeapons weapons, ITimer timer) : base(playerSettings, physicsComponent, null, weapons, timer) { LastReceivedPosition = this.Position; }
public void SetUp() { stubPhysicsComponent = MockRepository.GenerateStub<IPhysicsComponent>(); player = new NetworkPlayer(null, stubPhysicsComponent, MockRepository.GenerateStub<IWeapons>(), null); }
protected abstract void OnCollision(IPhysicsComponent physicsComponent, IPhysicsComponent colliding, Contact contact);
protected PullMessage(IPhysicsComponent puller, IPhysicsComponent pulled) { Puller = puller; Pulled = pulled; }
protected void UpdateKinematics(ITransformComponent transform, IMoverComponent mover, IPhysicsComponent physics, ICollidableComponent?collider = null) { physics.EnsureController <MoverController>(); var weightless = !transform.Owner.HasComponent <MovementIgnoreGravityComponent>() && _physicsManager.IsWeightless(transform.GridPosition); if (weightless && collider != null) { // No gravity: is our entity touching anything? var touching = IsAroundCollider(transform, mover, collider); if (!touching) { return; } } // TODO: movement check. var(walkDir, sprintDir) = mover.VelocityDir; var combined = walkDir + sprintDir; if (combined.LengthSquared < 0.001 || !ActionBlockerSystem.CanMove(mover.Owner) && !weightless) { if (physics.TryGetController(out MoverController controller)) { controller.StopMoving(); } } else { //Console.WriteLine($"{IoCManager.Resolve<IGameTiming>().TickStamp}: {combined}"); if (weightless) { if (physics.TryGetController(out MoverController controller)) { controller.Push(combined, mover.CurrentPushSpeed); } transform.LocalRotation = walkDir.GetDir().ToAngle(); return; } var total = walkDir * mover.CurrentWalkSpeed + sprintDir * mover.CurrentSprintSpeed; //Console.WriteLine($"{walkDir} ({mover.CurrentWalkSpeed}) + {sprintDir} ({mover.CurrentSprintSpeed}): {total}"); { if (physics.TryGetController(out MoverController controller)) { controller.Move(total, 1); } } transform.LocalRotation = total.GetDir().ToAngle(); HandleFootsteps(mover); } }
private void CollisionHandler(IPhysicsComponent source, IPhysicsComponent colliding, Contact contact) { if (colliding.Parent.HasMetadata("bottom")) { if (player != null) { int lives; int.TryParse(player.GetMetadata("lives").ToString(), NumberStyles.Integer,CultureInfo.InvariantCulture, out lives); if (lives == 0) { GameOver = true; StartGameOver(); } else { player.UpdateMetadata("lives", lives - 1); if (OnPlayerLivesChanged != null) OnPlayerLivesChanged(player, lives - 1); ResetBall(); } } } if (colliding.Parent.HasMetadata("brick")) //We've collided with a brick, check if they're all gone and, if so, you win! { IGameObject brick = gameObjectManager.FindWithMetadata("brick"); if (brick == null) StartWin(); } }
public void RemoveComponent(IPhysicsComponent component) { //_components.Remove(component); component.Physics.Enabled = false; _componentsToRemove.Add(component); }
public static Dictionary <string, Body> DeserializeBodies(XElement element, IPhysicsManager physicsManager, IPhysicsComponent parent) { Dictionary <string, Body> bodies = new Dictionary <string, Body>(); IEnumerable <XElement> elements = element.Elements("body"); foreach (XElement bodyElement in elements) { Body body = DeserializeBody(bodyElement, physicsManager, parent); if (body != null) { string name = ((FarseerUserData)body.UserData).Name; bodies.Add(name, body); } } return(bodies); }
public PullStartedMessage(IPhysicsComponent puller, IPhysicsComponent pulled) : base(puller, pulled) { }
public static Body DeserializeBody(XElement element, IPhysicsManager physicsManager, IPhysicsComponent parent) { Body body = null; FarseerUserData userData = new FarseerUserData(); //Read the shape used for this body. BodyType bodyType = BodyType.Static; if (element.Attribute("bodyType") != null) { if (element.Attribute("bodyType").Value.StartsWith("d", StringComparison.InvariantCultureIgnoreCase)) { bodyType = BodyType.Dynamic; } else if (element.Attribute("bodyType").Value.StartsWith("s", StringComparison.InvariantCultureIgnoreCase)) { bodyType = BodyType.Static; } else if (element.Attribute("bodyType").Value.StartsWith("k", StringComparison.InvariantCultureIgnoreCase)) { bodyType = BodyType.Kinematic; } } bool primary = false; if (element.Attribute("primary") != null) { bool.TryParse(element.Attribute("primary").Value, out primary); } Shape shape = null; XElement shapeElement = element.Element("shape"); if (shapeElement != null && shapeElement.Attribute("type") != null) { if (shapeElement.Attribute("type").Value.StartsWith("b", StringComparison.InvariantCultureIgnoreCase)) { shape = DeserializeBoxShape(shapeElement); } else if (shapeElement.Attribute("type").Value.StartsWith("c", StringComparison.InvariantCultureIgnoreCase)) { shape = DeserializeCircleShape(shapeElement); } else if (shapeElement.Attribute("type").Value.StartsWith("p", StringComparison.InvariantCultureIgnoreCase)) { shape = DeserializePolygonShape(shapeElement); } } if (shape != null) { string name; body = BodyFactory.CreateBody(physicsManager.PhysicsWorld); body.BodyType = bodyType; Vector2 offset = Vector2.Zero; float friction = 0.5f, linearDamping = 5f, restitution = 0f, mass = 1f; bool fixedRotation = false; if (element.Element("friction") != null) { float.TryParse(element.Element("friction").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out friction); } if (element.Element("linearDamping") != null) { float.TryParse(element.Element("linearDamping").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out linearDamping); } if (element.Element("restitution") != null) { float.TryParse(element.Element("restitution").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out restitution); } if (element.Element("mass") != null) { float.TryParse(element.Element("mass").Value, NumberStyles.Float, CultureInfo.InvariantCulture, out mass); } if (element.Element("fixedRotation") != null) { bool.TryParse(element.Element("fixedRotation").Value, out fixedRotation); } if (element.Element("offset") != null) { offset = offset.DeserializeOffset(element.Element("offset")); } body.CreateFixture(shape); body.Friction = friction; body.LinearDamping = linearDamping; body.Restitution = restitution; body.Mass = mass; body.FixedRotation = fixedRotation; name = element.Attribute("name") != null?element.Attribute("name").Value : body.BodyId.ToString(); userData.TopLeftOffset = ConvertUnits.GetTopLeftCorner(body.FixtureList[0], 0); userData.Name = name; userData.Primary = primary; userData.Owner = parent; userData.Offset = offset; body.UserData = userData; } return(body); }