示例#1
0
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                string      levelUid    = LevelSystem.currentLevelUid;
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    List <int> treeEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Tree);

                    // Update treeAABB
                    Vector2 screenCenter = _renderSystem.screenCenter;
                    float   halfWidth    = ((float)_renderSystem.screenWidth / _renderSystem.scale) / 2f;
                    float   halfHeight   = ((float)_renderSystem.screenHeight / _renderSystem.scale) / 2f;
                    treeAABB.LowerBound.X = screenCenter.X - halfWidth;
                    treeAABB.UpperBound.X = screenCenter.X + halfWidth;
                    treeAABB.LowerBound.Y = screenCenter.Y - halfHeight;
                    treeAABB.UpperBound.Y = screenCenter.Y + halfHeight;

                    prepareCollisions();

                    for (int i = 0; i < treeEntities.Count; i++)
                    {
                        TreeComponent treeComponent = (TreeComponent)_entityManager.getComponent(levelUid, treeEntities[i], ComponentType.Tree);
                        treeComponent.tree.update();
                    }
                }
            }
            _singleStep = false;
        }
示例#2
0
 public AIBehaviorSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;
     _random = new Random();
 }
示例#3
0
        public LevelScreen(LoderGame game, SystemManager systemManager, EntityManager entityManager)
            : base(game.screenSystem, ScreenType.Level)
        {
            _game = game;
            _systemManager = systemManager;
            _entityManager = entityManager;
            _levelSystem = (LevelSystem)_systemManager.getSystem(SystemType.Level);
            _content = new ContentManager(_game.Services);
            _content.RootDirectory = "Content";
            _equipmentSystem = (EquipmentSystem)_systemManager.getSystem(SystemType.Equipment);
            _playerId = PlayerSystem.PLAYER_ID;
            _pixel = new Texture2D(_game.GraphicsDevice, 1, 1);
            _pixel.SetData<Color>(new[] { Color.White });
            _arial = _content.Load<SpriteFont>("arial");
            _dialogePanes = new List<InteractiveDialoguePane>();
            _dialogueFont = _content.Load<SpriteFont>("shared_ui/dialogue_font");
            _dialogueOptionFont = _content.Load<SpriteFont>("shared_ui/dialogue_option_font");

            ToolbarComponent toolbarComponent = (ToolbarComponent)_entityManager.getComponent(LevelSystem.currentLevelUid, _playerId, ComponentType.Toolbar);

            _toolbarDisplay = new ToolbarDisplay(_game.spriteBatch, _equipmentSystem, toolbarComponent);
            _inventoryDisplay = new InventoryDisplay(_game.spriteBatch, _equipmentSystem, (InventoryComponent)_entityManager.getComponent(LevelSystem.currentLevelUid, _playerId, ComponentType.Inventory), toolbarComponent);
            _inventoryDisplay.inFocus = false;
            _toolbarDisplay.inFocus = true;

            _healthBar = new LargeHealthBar(_game.spriteBatch);
        }
示例#4
0
 public AIBehaviorSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _levelSystem   = _systemManager.getSystem(SystemType.Level) as LevelSystem;
     _random        = new Random();
 }
示例#5
0
 public EventSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _levelSystem   = (LevelSystem)_systemManager.getSystem(SystemType.Level);
     _handlers      = new Dictionary <GameEventType, Dictionary <int, List <IEventHandler> > >();
 }
示例#6
0
 public EventSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _levelSystem = (LevelSystem)_systemManager.getSystem(SystemType.Level);
     _handlers = new Dictionary<GameEventType,Dictionary<int,List<IEventHandler>>>();
 }
示例#7
0
        // onReturnToWorldMap -- Hook called when returning to the world map after a level ends
        public void onReturnToWorldMap(string key, LevelSystem levelSystem)
        {
            ScriptBase script = null;

            if (_scripts.TryGetValue(key, out script))
                script.onReturnToWorldMap(levelSystem);
        }
示例#8
0
        public void update(GameTime gameTime)
        {
            LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;
            string      levelUid    = LevelSystem.currentLevelUid;
            float       dt          = (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (levelSystem.finalized)
            {
                if (!_paused || _singleStep)
                {
                    List <int> characterRenderEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.CharacterRender);

                    for (int i = 0; i < characterRenderEntities.Count; i++)
                    {
                        CharacterRenderComponent   characterRenderComponent   = _entityManager.getComponent(levelUid, characterRenderEntities[i], ComponentType.CharacterRender) as CharacterRenderComponent;
                        CharacterMovementComponent characterMovementComponent = _entityManager.getComponent(levelUid, characterRenderEntities[i], ComponentType.CharacterMovement) as CharacterMovementComponent;
                        float changeRate = 1f / _animationManager.getFPS(characterRenderComponent.character, characterRenderComponent.animation);

                        // Handle time
                        characterRenderComponent.time += dt;
                        if (characterRenderComponent.time >= changeRate)
                        {
                            int currentFrame = characterRenderComponent.currentFrame;
                            int totalFrames  = _animationManager.getFrameCount(characterRenderComponent.character, characterRenderComponent.animation);
                            int nextFrame    = currentFrame + 1;

                            characterRenderComponent.currentFrame = nextFrame == totalFrames ? 0 : nextFrame;
                            characterRenderComponent.time        -= changeRate;
                        }

                        // Update animation
                        if (characterMovementComponent.walkLeft)
                        {
                            if (characterRenderComponent.animation != "walk_left")
                            {
                                setAnimation(characterRenderComponent, "walk_left");
                            }
                        }
                        else if (characterMovementComponent.walkRight)
                        {
                            if (characterRenderComponent.animation != "walk_right")
                            {
                                setAnimation(characterRenderComponent, "walk_right");
                            }
                        }
                        else
                        {
                            if (characterRenderComponent.animation != "idle")
                            {
                                setAnimation(characterRenderComponent, "idle");
                            }
                        }
                    }
                }
                _singleStep = false;
            }
        }
示例#9
0
        public void update(GameTime gameTime)
        {
            LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;
            string      levelUid    = LevelSystem.currentLevelUid;

            if (levelSystem.finalized)
            {
                if (!_paused || _singleStep)
                {
                }
                _singleStep = false;
            }
        }
示例#10
0
        // update
        public void update(GameTime gameTime)
        {
            LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

            if (InputSystem.newKeyState.IsKeyDown(Keys.F4) && InputSystem.oldKeyState.IsKeyUp(Keys.F4))
            {
                _enlargeDebugFuild = !_enlargeDebugFuild;
            }

            if (levelSystem.finalized)
            {
                _backgroundRenderer.update(_scale, -screenCenter);
            }
        }
示例#11
0
        // update
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                string      levelUid    = LevelSystem.currentLevelUid;
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    PhysicsComponent playerPhysicsComponent = (PhysicsComponent)_entityManager.getComponent(levelUid, PLAYER_ID, ComponentType.Physics);
                    bool             inDialogue             = _entityManager.getComponent(levelUid, PLAYER_ID, ComponentType.InDialogue) != null;

                    _oldKeyState = _newKeyState;
                    _newKeyState = Keyboard.GetState();

                    // Handle dialogue
                    handleDialogue(levelUid, playerPhysicsComponent, inDialogue);

                    // Handle character movement
                    handleCharacterMovement(levelUid, playerPhysicsComponent, inDialogue);
                }
            }
            _singleStep = false;
        }
示例#12
0
 public virtual void onGoalComplete(LevelSystem levelSystem, Goal goal)
 {
 }
示例#13
0
        // update
        public void update(GameTime gameTime)
        {
            if (_singleStep || !_paused)
            {
                string      levelUid    = LevelSystem.currentLevelUid;
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    PlayerSystem     playerSystem           = _systemManager.getSystem(SystemType.Player) as PlayerSystem;
                    RopeSystem       ropeSystem             = _systemManager.getSystem(SystemType.Rope) as RopeSystem;
                    PhysicsComponent playerPhysicsComponent = _entityManager.getComponent(levelUid, PlayerSystem.PLAYER_ID, ComponentType.Physics) as PhysicsComponent;
                    List <int>       toolbarEntities        = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Toolbar);

                    // Player equipment
                    if (playerSystem != null)
                    {
                        ToolbarComponent       playerToolbar           = _entityManager.getComponent(levelUid, PlayerSystem.PLAYER_ID, ComponentType.Toolbar) as ToolbarComponent;
                        WorldPositionComponent playerPositionComponent = _entityManager.getComponent(levelUid, PlayerSystem.PLAYER_ID, ComponentType.WorldPosition) as WorldPositionComponent;
                        ItemComponent          selectedItem            = playerToolbar.selectedItem;

                        if (selectedItem != null)
                        {
                            selectedItem.primaryContinuousAction   = InputSystem.newMouseState.LeftButton == ButtonState.Pressed;
                            selectedItem.primarySingleAction       = selectedItem.primaryContinuousAction && InputSystem.oldMouseState.LeftButton == ButtonState.Released;
                            selectedItem.secondaryContinuousAction = InputSystem.newMouseState.RightButton == ButtonState.Pressed;
                            selectedItem.secondarySingleAction     = selectedItem.secondaryContinuousAction && InputSystem.oldMouseState.RightButton == ButtonState.Released;
                            //bool leftTriggerDown = InputSystem.usingGamepad && InputSystem.newGamepadState.Triggers.Left > 0.5f && InputSystem.oldGamepadState.Triggers.Left <= 0.5f;
                            //bool rightTriggerDown = InputSystem.usingGamepad && InputSystem.newGamepadState.Triggers.Right > 0.5f && InputSystem.oldGamepadState.Triggers.Right <= 0.5f;
                            AimComponent aimComponent = _entityManager.getComponent(levelUid, PlayerSystem.PLAYER_ID, ComponentType.Aim) as AimComponent;

                            if (selectedItem.definition.hasAimingComponent && aimComponent != null)
                            {
                                WorldPositionComponent worldPositionComponent = _entityManager.getComponent(levelUid, PlayerSystem.PLAYER_ID, ComponentType.WorldPosition) as WorldPositionComponent;

                                if (worldPositionComponent != null)
                                {
                                    Vector2 worldPosition = worldPositionComponent.position;
                                    if (InputSystem.usingGamepad)
                                    {
                                        Vector2 vector = InputSystem.newGamepadState.ThumbSticks.Left * selectedItem.state.currentRangeLimit;
                                        vector.Y           *= -1;
                                        aimComponent.angle  = (float)Math.Atan2(vector.Y, vector.X);
                                        aimComponent.length = vector.Length();
                                        aimComponent.vector = vector;
                                    }
                                    else
                                    {
                                        Vector2 relative = (InputSystem.worldMouse - worldPosition);
                                        aimComponent.angle  = (float)Math.Atan2(relative.Y, relative.X);
                                        aimComponent.length = Math.Min(relative.Length(), selectedItem.state.currentRangeLimit);
                                        aimComponent.vector = relative;
                                    }
                                }
                            }
                        }
                    }

                    // All toolbars
                    for (int i = 0; i < toolbarEntities.Count; i++)
                    {
                        ToolbarComponent toolbarComponent = _entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.Toolbar) as ToolbarComponent;
                        ItemComponent    selectedItem     = toolbarComponent.selectedItem;

                        if (selectedItem != null)
                        {
                            if (selectedItem.secondarySingleAction)
                            {
                                Console.WriteLine("secondary action");
                            }

                            switch (selectedItem.definition.uid)
                            {
                            // RopeGun
                            case "ropegun":
                                if (selectedItem.primarySingleAction)
                                {
                                    AimComponent aimComponent  = _entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.Aim) as AimComponent;
                                    Vector2      initialPointA = (_entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.WorldPosition) as WorldPositionComponent).position;
                                    Vector2      initialPointB = initialPointA + new Vector2((float)Math.Cos(aimComponent.angle), (float)Math.Sin(aimComponent.angle)) * aimComponent.length;
                                    int          ropeEntityId  = _entityManager.factory.createSingleAnchorRope(levelUid, initialPointA, initialPointB, _defaultRopeMaterial, true);

                                    if (ropeEntityId != -1)
                                    {
                                        RopeGrabComponent ropeGrabComponent    = _entityManager.getComponent(levelUid, toolbarComponent.entityId, ComponentType.RopeGrab) as RopeGrabComponent;
                                        RopeComponent     ropeComponent        = _entityManager.getComponent(levelUid, ropeEntityId, ComponentType.Rope) as RopeComponent;
                                        PhysicsComponent  physicsComponent     = _entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.Physics) as PhysicsComponent;
                                        RopeGrabComponent newRopeGrabComponent = null;
                                        Vector2           initialVelocity      = physicsComponent.body.LinearVelocity;
                                        RopeNode          currentNode          = null;
                                        int ropeSegmentCount;

                                        if (physicsComponent == null)
                                        {
                                            break;
                                        }

                                        // Handle initial velocity
                                        currentNode      = ropeComponent.ropeNodeHead;
                                        ropeSegmentCount = currentNode.count;
                                        System.Diagnostics.Debug.Assert(ropeSegmentCount != 0);
                                        int count = ropeSegmentCount;
                                        while (currentNode != null)
                                        {
                                            float weight = (float)count / (float)ropeSegmentCount;

                                            currentNode.body.LinearVelocity = currentNode.body.LinearVelocity + initialVelocity * weight;

                                            count--;
                                            currentNode = currentNode.next;
                                        }

                                        // Handle previous grabs
                                        if (ropeGrabComponent != null)
                                        {
                                            RopeComponent previouslyGrabbedRope = _entityManager.getComponent(levelUid, ropeGrabComponent.ropeEntityId, ComponentType.Rope) as RopeComponent;
                                            ropeSystem.releaseRope(ropeGrabComponent, physicsComponent.body);

                                            if (previouslyGrabbedRope.destroyAfterRelease)
                                            {
                                                previouslyGrabbedRope.timeToLive = 100;
                                            }
                                            _entityManager.removeComponent(levelUid, toolbarComponent.entityId, ropeGrabComponent);
                                            ropeGrabComponent = null;
                                        }

                                        newRopeGrabComponent = new RopeGrabComponent(ropeEntityId, ropeComponent.ropeNodeHead, 0f, ropeComponent.reverseClimbDirection);
                                        ropeSystem.grabRope(newRopeGrabComponent, physicsComponent.body);
                                        _entityManager.addComponent(levelUid, toolbarComponent.entityId, newRopeGrabComponent);
                                    }
                                }
                                break;

                            // Dynamite
                            case "dynamite":
                                if (selectedItem.primarySingleAction)
                                {
                                    AimComponent aimComponent = _entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.Aim) as AimComponent;

                                    _entityManager.factory.createDynamite(levelUid, playerPhysicsComponent.body.Position, aimComponent.vector * 80f);
                                }
                                break;

                            // Water gun
                            case "watergun":
                                if (selectedItem.primaryContinuousAction)
                                {
                                    FluidSystem  fluidSystem      = _systemManager.getSystem(SystemType.Fluid) as FluidSystem;
                                    AimComponent aimComponent     = _entityManager.getComponent(levelUid, toolbarEntities[i], ComponentType.Aim) as AimComponent;
                                    Vector2      aimUnitVector    = Vector2.Normalize(aimComponent.vector);
                                    Vector2      particlePosition =
                                        playerPhysicsComponent.body.Position +
                                        aimUnitVector +
                                        new Vector2(StasisMathHelper.floatBetween(-0.1f, 0.1f, _rng), StasisMathHelper.floatBetween(-0.1f, 0.1f, _rng));
                                    Vector2 particleVelocity = aimUnitVector * 0.4f;

                                    fluidSystem.createParticle(particlePosition, particleVelocity);
                                }
                                break;
                            }

                            selectedItem.primarySingleAction       = false;
                            selectedItem.secondarySingleAction     = false;
                            selectedItem.primaryContinuousAction   = false;
                            selectedItem.secondaryContinuousAction = false;
                        }
                    }
                }
            }
            _singleStep = false;
        }
示例#14
0
 // startPersistentSystems -- Certain systems (such as WorldMap, Level, Player, etc...) that need to be active throughout the entire game
 public void startPersistentSystems()
 {
     _playerSystem = new PlayerSystem(_systemManager, _entityManager);
     _equipmentSystem = new EquipmentSystem(_systemManager, _entityManager);
     _levelSystem = new LevelSystem(this, _systemManager, _entityManager);
     _systemManager.add(_playerSystem, -1);
     _systemManager.add(_equipmentSystem, -1);
     _systemManager.add(_levelSystem, -1);
 }
示例#15
0
        public void update(GameTime gameTime)
        {
            string       levelUid     = LevelSystem.currentLevelUid;
            LevelSystem  levelSystem  = _systemManager.getSystem(SystemType.Level) as LevelSystem;
            RenderSystem renderSystem = _systemManager.getSystem(SystemType.Render) as RenderSystem;

            if (levelSystem.finalized)
            {
                float speed = 0.1f;
                List <BodyFocusPointComponent> bodyFocusPoints = _entityManager.getComponents <BodyFocusPointComponent>(levelUid, ComponentType.BodyFocusPoint);
                Vector2 singleTarget        = _screenCenter;
                Vector2 multipleTarget      = Vector2.Zero;
                bool    useSingleTarget     = false;
                int     multipleTargetCount = 0;

                // Handle manual camera movement
                if (_enableManualMovement)
                {
                    if (InputSystem.newKeyState.IsKeyDown(Keys.NumPad8))
                    {
                        _screenCenter += new Vector2(0, -speed);
                    }
                    if (InputSystem.newKeyState.IsKeyDown(Keys.NumPad2))
                    {
                        _screenCenter += new Vector2(0, speed);
                    }
                    if (InputSystem.newKeyState.IsKeyDown(Keys.NumPad4))
                    {
                        _screenCenter += new Vector2(-speed, 0);
                    }
                    if (InputSystem.newKeyState.IsKeyDown(Keys.NumPad6))
                    {
                        _screenCenter += new Vector2(speed, 0);
                    }
                    //if (InputSystem.newKeyState.IsKeyDown(Keys.F4))
                    //    Console.WriteLine("Screen center: {0}", _screenCenter);
                }

                // Handle camera movement
                if (!_paused || _singleStep)
                {
                    AABB    boundary         = levelSystem.getBoundary(levelUid);
                    Vector2 scaledHalfScreen = renderSystem.halfScreen / renderSystem.scale;

                    for (int i = 0; i < bodyFocusPoints.Count; i++)
                    {
                        if (bodyFocusPoints[i].focusType == FocusType.Multiple)
                        {
                            multipleTarget += bodyFocusPoints[i].focusPoint;
                            multipleTargetCount++;
                        }
                        else if (bodyFocusPoints[i].focusType == FocusType.Single)
                        {
                            singleTarget    = bodyFocusPoints[i].focusPoint;
                            useSingleTarget = true;
                            break;
                        }
                    }

                    if (useSingleTarget)
                    {
                        _screenCenter += (singleTarget - _screenCenter) / 2f;
                    }
                    else
                    {
                        _screenCenter += (multipleTarget / multipleTargetCount - _screenCenter) / 2f;
                    }

                    // Enforce edge boundaries
                    _screenCenter = Vector2.Max(_screenCenter, boundary.LowerBound + scaledHalfScreen);
                    _screenCenter = Vector2.Min(_screenCenter, boundary.UpperBound - scaledHalfScreen);

                    _singleStep = false;
                }
            }
        }
示例#16
0
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                string      levelUid    = LevelSystem.currentLevelUid;
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    List <int> ropeEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Rope);

                    for (int i = 0; i < ropeEntities.Count; i++)
                    {
                        RopeComponent     ropeComponent     = _entityManager.getComponent(levelUid, ropeEntities[i], ComponentType.Rope) as RopeComponent;
                        RopeGrabComponent ropeGrabComponent = _entityManager.getComponent(levelUid, ropeEntities[i], ComponentType.RopeGrab) as RopeGrabComponent;
                        RopeNode          head    = ropeComponent.ropeNodeHead;
                        RopeNode          current = head;
                        RopeNode          tail    = head.tail;

                        // Check segment length
                        if (head.count < 3 && ropeGrabComponent == null)
                        {
                            ropeComponent.startTTLCountdown();
                        }

                        // Check anchors
                        if (head.anchorJoint == null && tail.anchorJoint == null)
                        {
                            ropeComponent.startTTLCountdown();
                        }

                        // Check time to live
                        if (ropeComponent.timeToLive == 0)
                        {
                            killRope(levelUid, ropeEntities[i]);
                            ropeComponent.timeToLive--;
                        }
                        else if (ropeComponent.timeToLive > -1)
                        {
                            ropeComponent.timeToLive--;
                        }

                        while (current != null)
                        {
                            // Check tensions
                            if (current.joint != null)
                            {
                                Vector2 relative;
                                if (current == head || current == tail)
                                {
                                    // Check anchor joint
                                    if (current.anchorJoint != null)
                                    {
                                        relative = current.anchorJoint.BodyA.GetWorldPoint(current.anchorJoint.LocalAnchorA) -
                                                   current.anchorJoint.BodyB.GetWorldPoint(current.anchorJoint.LocalAnchorB);
                                        if (relative.Length() > 0.8f || current.anchorJoint.GetReactionForce(60f).Length() > 400f)
                                        {
                                            breakAnchor(current);
                                        }
                                    }
                                }

                                // Check other joints
                                relative = current.joint.BodyA.GetWorldPoint(current.joint.LocalAnchorA) -
                                           current.joint.BodyB.GetWorldPoint(current.joint.LocalAnchorB);
                                if (relative.Length() > 1.2f || current.joint.GetReactionForce(60f).Length() > 300f)
                                {
                                    breakJoint(levelUid, ropeEntities[i], current);
                                }
                            }
                            current = current.next;
                        }
                    }
                }
            }
            _singleStep = false;
        }
示例#17
0
        public bool BeginContact(Contact contact)
        {
            string          levelUid          = LevelSystem.currentLevelUid;
            List <int>      levelGoalEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.RegionGoal);
            List <int>      explosionEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Explosion);
            LevelSystem     levelSystem       = (LevelSystem)_systemManager.getSystem(SystemType.Level);
            ExplosionSystem explosionSystem   = (ExplosionSystem)_systemManager.getSystem(SystemType.Explosion);
            int             playerId          = PlayerSystem.PLAYER_ID;

            // See if player is touching a level goal
            if (levelGoalEntities.Count > 0)
            {
                int entityA = (int)contact.FixtureA.Body.UserData;
                int entityB = (int)contact.FixtureB.Body.UserData;

                if (entityA == playerId)
                {
                    if (levelGoalEntities.Contains(entityB))
                    {
                        levelSystem.completeRegionGoal(entityB);
                    }
                }
                else if (entityB == playerId)
                {
                    if (levelGoalEntities.Contains(entityA))
                    {
                        levelSystem.completeRegionGoal(entityA);
                    }
                }
            }

            // Explosions
            if (explosionEntities.Count > 0)
            {
                int                   entityA            = (int)contact.FixtureA.Body.UserData;
                int                   entityB            = (int)contact.FixtureB.Body.UserData;
                IComponent            component          = null;
                ExplosionComponent    explosionComponent = null;
                Fixture               targetFixture      = null;
                FixedArray2 <Vector2> points;

                if (_entityManager.tryGetComponent(levelUid, entityA, ComponentType.Explosion, out component))
                {
                    targetFixture = contact.FixtureB;
                }
                else if (_entityManager.tryGetComponent(levelUid, entityB, ComponentType.Explosion, out component))
                {
                    targetFixture = contact.FixtureA;
                }

                if (targetFixture != null && component != null)
                {
                    DestructibleGeometryComponent destructibleGeometryComponent = (DestructibleGeometryComponent)_entityManager.getComponent(levelUid, (int)targetFixture.Body.UserData, ComponentType.DestructibleGeometry);
                    Vector2 contactNormal;
                    Vector2 relative;
                    Vector2 force;
                    float   distance;

                    //contact.GetWorldManifold(out worldManifold);
                    contact.GetWorldManifold(out contactNormal, out points);
                    explosionComponent = (ExplosionComponent)component;
                    relative           = (targetFixture.Shape.Center + targetFixture.Body.Position) - explosionComponent.position;
                    distance           = Math.Max(relative.Length(), 0.1f);
                    force = relative * (1 / distance) * explosionComponent.strength;

                    if (destructibleGeometryComponent != null)
                    {
                        // Break fixture off from body
                        explosionSystem.breakFixture(targetFixture, force, 180);
                        return(false);
                    }
                    else
                    {
                        // Apply generic explosion force
                        targetFixture.Body.ApplyForce(force, points[0]);
                        return(false);
                    }
                }
            }

            return(true);
        }
示例#18
0
        public void update(GameTime gameTime)
        {
            if (_singleStep || !_paused)
            {
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    string      levelUid    = LevelSystem.currentLevelUid;
                    EventSystem eventSystem = _systemManager.getSystem(SystemType.Event) as EventSystem;
                    List <CharacterMovementComponent> movementComponents = _entityManager.getComponents <CharacterMovementComponent>(levelUid, ComponentType.CharacterMovement);
                    List <int> ropeGrabEntities  = _entityManager.getEntitiesPosessing(levelUid, ComponentType.RopeGrab);
                    List <int> prismaticEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Prismatic);
                    List <int> physicsEntities;

                    for (int i = 0; i < _bodiesToRemove.Count; i++)
                    {
                        getWorld(levelUid).RemoveBody(_bodiesToRemove[i]);
                    }
                    _bodiesToRemove.Clear();

                    for (int i = 0; i < movementComponents.Count; i++)
                    {
                        CharacterMovementComponent movementComponent = movementComponents[i];

                        movementComponent.collisionNormals.Clear();
                    }

                    for (int i = 0; i < prismaticEntities.Count; i++)
                    {
                        PrismaticJointComponent prismaticJointComponent = _entityManager.getComponent(levelUid, prismaticEntities[i], ComponentType.Prismatic) as PrismaticJointComponent;
                        LimitState limitState = prismaticJointComponent.prismaticJoint.LimitState;

                        if (prismaticJointComponent.previousLimitState != limitState)
                        {
                            if (limitState == LimitState.AtLower)
                            {
                                eventSystem.postEvent(new GameEvent(GameEventType.OnLowerLimitReached, prismaticEntities[i]));
                            }
                            else if (limitState == LimitState.AtUpper)
                            {
                                //eventSystem.postEvent(new GameEvent(GameEventType.OnUpperLimitReached, prismaticEntities[i]));
                            }
                        }

                        prismaticJointComponent.previousLimitState = limitState;
                    }

                    getWorld(levelUid).Step(_dt);

                    // Handle physic entities
                    physicsEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Physics);
                    for (int i = 0; i < physicsEntities.Count; i++)
                    {
                        PhysicsComponent       physicsComponent       = _entityManager.getComponent(levelUid, physicsEntities[i], ComponentType.Physics) as PhysicsComponent;
                        WorldPositionComponent worldPositionComponent = _entityManager.getComponent(levelUid, physicsEntities[i], ComponentType.WorldPosition) as WorldPositionComponent;
                        FollowMetamerComponent followMetamerComponent = _entityManager.getComponent(levelUid, physicsEntities[i], ComponentType.FollowMetamer) as FollowMetamerComponent;

                        // Set body position to the metamer being followed
                        if (followMetamerComponent != null)
                        {
                            physicsComponent.body.Position = followMetamerComponent.metamer.position;
                            physicsComponent.body.Rotation = followMetamerComponent.metamer.currentAngle + StasisMathHelper.halfPi;
                        }

                        // Update world position component
                        worldPositionComponent.position = physicsComponent.body.Position;
                    }
                }
            }
            _singleStep = false;
        }
示例#19
0
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    string     levelUid          = LevelSystem.currentLevelUid;
                    List <int> characterEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.CharacterMovement);

                    for (int i = 0; i < characterEntities.Count; i++)
                    {
                        PhysicsComponent           physicsComponent           = _entityManager.getComponent(levelUid, characterEntities[i], ComponentType.Physics) as PhysicsComponent;
                        ParticleInfluenceComponent particleInfluenceComponent = _entityManager.getComponent(levelUid, characterEntities[i], ComponentType.ParticleInfluence) as ParticleInfluenceComponent;
                        CharacterMovementComponent characterMovementComponent = _entityManager.getComponent(levelUid, characterEntities[i], ComponentType.CharacterMovement) as CharacterMovementComponent;
                        RopeGrabComponent          ropeGrabComponent          = _entityManager.getComponent(levelUid, characterEntities[i], ComponentType.RopeGrab) as RopeGrabComponent;
                        Body  body         = physicsComponent.body;
                        float currentSpeed = body.LinearVelocity.Length();

                        // Handle fluid properties
                        characterMovementComponent.inFluid = particleInfluenceComponent.particleCount > 2;

                        // Handle rope grabs
                        if (characterMovementComponent.allowRopeGrab && characterMovementComponent.doRopeGrab)
                        {
                            attemptRopeGrab(levelUid, characterEntities[i], characterMovementComponent, physicsComponent, ropeGrabComponent);
                        }

                        // Calculate movement vector
                        if (characterMovementComponent.collisionNormals.Count > 0)
                        {
                            characterMovementComponent.movementUnitVector = Vector2.Zero;
                            for (int j = 0; j < characterMovementComponent.collisionNormals.Count; j++)
                            {
                                characterMovementComponent.movementUnitVector += characterMovementComponent.collisionNormals[j] / characterMovementComponent.collisionNormals.Count;
                            }
                            characterMovementComponent.movementUnitVector = new Vector2(characterMovementComponent.movementUnitVector.Y, -characterMovementComponent.movementUnitVector.X);
                            characterMovementComponent.movementUnitVector.Normalize();
                        }
                        else
                        {
                            characterMovementComponent.movementUnitVector = new Vector2(-1, 0);
                        }

                        // On surface movement
                        if (characterMovementComponent.onSurface)
                        {
                            if (characterMovementComponent.walkLeft || characterMovementComponent.walkRight)
                            {
                                // Adjust friction
                                if (body.LinearVelocity.X < -0.1f && characterMovementComponent.walkRight)
                                {
                                    body.Friction = 10f;
                                }
                                else if (body.LinearVelocity.X > 0.1f && characterMovementComponent.walkLeft)
                                {
                                    body.Friction = 10f;
                                }
                                else
                                {
                                    body.Friction = 0.1f;
                                }

                                // Walk
                                if (currentSpeed <= characterMovementComponent.speedLimit)
                                {
                                    Vector2 impulse = characterMovementComponent.movementUnitVector * _baseWalkMultiplier;

                                    if (characterMovementComponent.walkRight)
                                    {
                                        impulse *= -1;
                                    }
                                    if (characterMovementComponent.inFluid)
                                    {
                                        impulse *= 0.5f;
                                    }
                                    body.ApplyLinearImpulse(ref impulse);
                                }
                            }
                            else
                            {
                                body.Friction = 10f;
                            }
                        }
                        else  // In-air movement
                        {
                            if (characterMovementComponent.walkLeft || characterMovementComponent.walkRight)
                            {
                                if (ropeGrabComponent != null)
                                {
                                    // Swing
                                    Vector2 impulse = characterMovementComponent.movementUnitVector * _baseSwingMultiplier;

                                    if (characterMovementComponent.walkRight)
                                    {
                                        impulse *= -1;
                                    }

                                    body.ApplyLinearImpulse(ref impulse);
                                }
                                else
                                {
                                    // Air walk
                                    if ((body.LinearVelocity.X < 0 && characterMovementComponent.walkRight) ||
                                        (body.LinearVelocity.X > 0 && characterMovementComponent.walkLeft) ||
                                        (body.LinearVelocity.X > -characterMovementComponent.speedLimit && characterMovementComponent.walkLeft) ||
                                        (body.LinearVelocity.X < characterMovementComponent.speedLimit && characterMovementComponent.walkRight))
                                    {
                                        Vector2 impulse = characterMovementComponent.movementUnitVector * _baseAirWalkMultiplier;

                                        if (characterMovementComponent.walkRight)
                                        {
                                            impulse *= -1;
                                        }

                                        body.ApplyLinearImpulse(ref impulse);
                                    }
                                }
                            }
                        }

                        // Jump
                        if (characterMovementComponent.attemptJump)
                        {
                            // While holding rope
                            if (ropeGrabComponent != null)
                            {
                                RopeComponent ropeComponent = _entityManager.getComponent(levelUid, ropeGrabComponent.ropeEntityId, ComponentType.Rope) as RopeComponent;
                                Vector2       impulse       = new Vector2(0, -1.2f);

                                if (ropeComponent != null && ropeComponent.destroyAfterRelease)
                                {
                                    ropeComponent.timeToLive = 100;
                                }

                                _ropeSystem.releaseRope(ropeGrabComponent, physicsComponent.body);
                                _entityManager.removeComponent(levelUid, characterEntities[i], ropeGrabComponent);
                                ropeGrabComponent = null;

                                body.ApplyLinearImpulse(ref impulse);
                            }

                            if (characterMovementComponent.onSurface)
                            {
                                Vector2 impulse    = new Vector2(0, -2f);
                                float   adjustment = 0f;

                                // Try to limit the impulse based on the current y velocity.
                                // This is done to prevent jumps from contributing too much to the y velocity when
                                // the player is already moving upwards too fast (which results in a super-jump).
                                adjustment = (body.LinearVelocity.Y / 6f);
                                impulse.Y -= adjustment;

                                body.ApplyLinearImpulse(ref impulse);
                                characterMovementComponent.attemptJump = false;
                            }
                        }

                        // Swim
                        if (characterMovementComponent.inFluid && characterMovementComponent.swimUp)
                        {
                            Vector2 impulse = new Vector2(0, -0.25f);

                            body.ApplyLinearImpulse(ref impulse);
                        }

                        // Climbing
                        if (ropeGrabComponent != null)
                        {
                            float climbSpeed = characterMovementComponent.climbAmount * CLIMB_SPEED;
                            if (characterMovementComponent.climbUp)
                            {
                                _ropeSystem.moveAttachedBody(ropeGrabComponent, physicsComponent.body, climbSpeed);
                            }
                            else if (characterMovementComponent.climbDown)
                            {
                                _ropeSystem.moveAttachedBody(ropeGrabComponent, physicsComponent.body, -climbSpeed);
                            }
                        }
                    }
                }
            }
            _singleStep = false;
        }
示例#20
0
        // Update
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                string      levelUid    = LevelSystem.currentLevelUid;
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    List <ParticleInfluenceComponent> particleInfluenceComponents = _entityManager.getComponents <ParticleInfluenceComponent>(levelUid, ComponentType.ParticleInfluence);

                    // Reset particle influence components
                    for (int i = 0; i < particleInfluenceComponents.Count; i++)
                    {
                        particleInfluenceComponents[i].particleCount = 0;
                    }

                    if (!_skipAABBUpdate)
                    {
                        // Update simulation AABB
                        Vector2 screenCenter  = _renderSystem.screenCenter;
                        Vector2 simHalfScreen = (_renderSystem.halfScreen / _renderSystem.scale) + SIMULATION_MARGIN;
                        simulationAABB.LowerBound = screenCenter - simHalfScreen;
                        simulationAABB.UpperBound = screenCenter + simHalfScreen;
                    }

                    // Flag active particles
                    flagActive();

                    // Prepare simulation
                    Parallel.For(0, numActiveParticles, i => { prepareSimulation(activeParticles[i]); });

                    // Prepare collisions
                    prepareCollisions();

                    // Calculate pressures
                    Parallel.For(0, numActiveParticles, i => { calculatePressure(activeParticles[i]); });

                    // Calculate forces
                    Parallel.For(
                        0,
                        numActiveParticles,
                        () => new Vector2[MAX_PARTICLES],
                        (i, state, accumulatedDelta) => calculateForce(activeParticles[i], accumulatedDelta),
                        (accumulatedDelta) =>
                    {
                        lock (_calculateForcesLock)
                        {
                            for (int i = numActiveParticles - 1; i >= 0; i--)
                            {
                                _delta[activeParticles[i]] += accumulatedDelta[activeParticles[i]] / MULTIPLIER;
                            }
                        }
                    }
                        );

                    // Resolve collisions
                    Parallel.For(0, numActiveParticles, i => resolveCollision(levelUid, activeParticles[i]));

                    // Move particles
                    Parallel.For(0, numActiveParticles, i =>
                    {
                        int index         = activeParticles[i];
                        Particle particle = liquid[index];

                        if (!particle.skipMovementUpdate)
                        {
                            Vector2 newVelocity = particle.velocity + _delta[index] + _gravity;
                            Vector2 newPosition = particle.position + _delta[index] + newVelocity;

                            if (isInBounds(ref newPosition))
                            {
                                particle.velocity = newVelocity;
                                particle.position = newPosition;
                            }
                        }
                    });

                    // Update particles
                    for (int i = numActiveParticles - 1; i >= 0; i--)
                    {
                        updateParticle(levelUid, activeParticles[i]);
                    }
                }
            }
            _singleStep = false;
        }
示例#21
0
 public virtual void onReturnToWorldMap(LevelSystem levelSystem)
 {
 }
示例#22
0
        public void update(GameTime gameTime)
        {
            if (!_paused || _singleStep)
            {
                LevelSystem levelSystem = _systemManager.getSystem(SystemType.Level) as LevelSystem;

                if (levelSystem.finalized)
                {
                    string     levelUid          = LevelSystem.currentLevelUid;
                    List <int> dynamiteEntities  = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Dynamite);
                    List <int> explosionEntities = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Explosion);
                    List <int> debrisEntities    = _entityManager.getEntitiesPosessing(levelUid, ComponentType.Debris);

                    // Dynamite entities
                    for (int i = 0; i < dynamiteEntities.Count; i++)
                    {
                        DynamiteComponent dynamiteComponent = (DynamiteComponent)_entityManager.getComponent(levelUid, dynamiteEntities[i], ComponentType.Dynamite);

                        if (dynamiteComponent.timeToLive > 0)
                        {
                            dynamiteComponent.timeToLive--;
                        }
                        else
                        {
                            explodeDynamite(levelUid, dynamiteEntities[i], dynamiteComponent);
                        }
                    }

                    // Explosion entities -- Explosion contact logic is handled by the PhysicsSystem's contact listeners. This just removes them, since they only should exist for 1 frame
                    for (int i = 0; i < explosionEntities.Count; i++)
                    {
                        PhysicsComponent physicsComponent = (PhysicsComponent)_entityManager.getComponent(levelUid, explosionEntities[i], ComponentType.Physics);

                        physicsComponent.body.World.RemoveBody(physicsComponent.body);
                        _entityManager.killEntity(levelUid, explosionEntities[i]);
                    }

                    // Break fixtures and create debris
                    for (int i = 0; i < _debrisToCreate.Count; i++)
                    {
                        Fixture fixture = _debrisToCreate[i].fixture;

                        if (fixture.Shape != null)
                        {
                            int entityId = (int)fixture.Body.UserData;
                            PrimitivesRenderComponent primitiveRenderComponent = (PrimitivesRenderComponent)_entityManager.getComponent(levelUid, entityId, ComponentType.PrimitivesRender);
                            PrimitiveRenderObject     primitiveRenderObject    = primitiveRenderComponent.primitiveRenderObjects[0];
                            RenderableTriangle        triangleToRemove         = null;

                            for (int j = 0; j < primitiveRenderObject.renderableTriangles.Count; j++)
                            {
                                if (primitiveRenderObject.renderableTriangles[j].fixture == fixture)
                                {
                                    triangleToRemove = primitiveRenderObject.renderableTriangles[j];
                                    break;
                                }
                            }
                            if (triangleToRemove != null)
                            {
                                primitiveRenderObject.renderableTriangles.Remove(triangleToRemove);
                            }

                            _entityManager.factory.createDebris(levelUid, fixture, _debrisToCreate[i].force, _debrisToCreate[i].timeToLive, triangleToRemove, primitiveRenderObject.texture, primitiveRenderObject.layerDepth);
                            fixture.Body.DestroyFixture(fixture);
                        }
                    }
                    _debrisToCreate.Clear();

                    // Debris
                    for (int i = 0; i < debrisEntities.Count; i++)
                    {
                        DebrisComponent debrisComponent = (DebrisComponent)_entityManager.getComponent(levelUid, debrisEntities[i], ComponentType.Debris);
                        debrisComponent.timeToLive--;

                        if (debrisComponent.restitutionCount < DebrisComponent.RESTITUTION_RESTORE_COUNT)
                        {
                            debrisComponent.fixture.Restitution = debrisComponent.fixture.Restitution + debrisComponent.restitutionIncrement;
                        }

                        if (debrisComponent.timeToLive < 0)
                        {
                            killDebris(levelUid, debrisEntities[i]);
                        }
                    }
                }
            }
            _singleStep = false;
        }
示例#23
0
 public virtual void registerGoals(LevelSystem levelSystem)
 {
 }
示例#24
0
        // registerGoals -- Hook for registering goals for a specific level
        public void registerGoals(string key, LevelSystem levelSystem)
        {
            ScriptBase script = null;

            if (_scripts.TryGetValue(key, out script))
            {
                script.registerGoals(levelSystem);
            }
        }