Example #1
0
        protected override void OnUpdate()
        {
            for (int i = 0; i < FollowEntities.Length; i++)
            {
                Transform         trans = FollowEntities.Transforms[i];
                FollowComponent   fc    = FollowEntities.FollowComponents[i];
                VelocityComponent vc    = FollowEntities.VelocityComponents[i];

                Vector3 direction = trans.InverseTransformDirection(fc.followTrans.position - trans.position);

                if (direction.magnitude < fc.stopDistance)
                {
                    vc.inputX = Mathf.Lerp(vc.inputX, 0, Time.deltaTime * 3);
                    vc.inputY = Mathf.Lerp(vc.inputY, 0, Time.deltaTime * 3);
                }
                else
                {
                    direction.Normalize();

                    vc.inputX = Mathf.Lerp(vc.inputX, direction.x, Time.deltaTime * 3);
                    vc.inputY = Mathf.Lerp(vc.inputY, direction.z, Time.deltaTime * 3);
                }
            }

            for (int i = 0; i < LookAtEntities.Length; i++)
            {
                Transform        trans   = LookAtEntities.Transforms[i];
                LookAtComponent  lookAt  = LookAtEntities.LookAtComponents[i];
                HeadingComponent heading = LookAtEntities.HeadingComponents[i];

                Vector3 direction = lookAt.lookTrans.position - trans.position;

                trans.rotation = Quaternion.Lerp(trans.rotation, Quaternion.LookRotation(direction), Time.deltaTime * heading.angularSpeed);
            }
        }
Example #2
0
    void applyAcceleration(Entity e, float deltaTime)
    {
        AccelerationComponent acceleration = e.acceleration;
        VelocityComponent     velocity     = e.velocity;

        acceleration.x = getAcceleration(acceleration.x, acceleration.frictionX, deltaTime);
        acceleration.y = getAcceleration(acceleration.y, acceleration.frictionY, deltaTime);

        velocity.vel += new Vector2(acceleration.x * deltaTime, acceleration.y * deltaTime);

        if (acceleration.stopNearZero)           // todo
        {
            int count = 0;
            if (Mathf.Abs(velocity.vel.x) < EPSILON)
            {
                velocity.vel.x = 0.0f;
                count++;
            }
            if (Mathf.Abs(velocity.vel.y) < EPSILON)
            {
                velocity.vel.y = 0.0f;
                count++;
            }
            if (count == 2)
            {
                e.RemoveAcceleration();
            }
        }
    }
Example #3
0
 public RocketEntity(GameEntity rocketE)
 {
     FirePower = rocketE.firePower;
     Health    = rocketE.health;
     Position  = rocketE.position;
     Velocity  = rocketE.velocity;
 }
Example #4
0
        public override void Process(Entity entity)
        {
            VelocityComponent velocityComponent = entity.GetComponent <VelocityComponent>();
            PositionComponent positionComponent = entity.GetComponent <PositionComponent>();

            positionComponent.Position += velocityComponent.Velocity * (float)DeltaTime.TotalSeconds;

            float speed = velocityComponent.Velocity.Length();

            if (speed > 0f)
            {
                float newSpeed = speed - velocityComponent.Friction * (float)DeltaTime.TotalSeconds;
                float ratio    = newSpeed / speed;
                if (ratio < 0f)
                {
                    ratio = 0f;
                }
                velocityComponent.Velocity *= ratio;
                speed = newSpeed;
            }

            if (speed > velocityComponent.MaxSpeed)
            {
                velocityComponent.Velocity *= velocityComponent.MaxSpeed / speed;
            }
        }
Example #5
0
        //You must have an Update.
        public override void Update(float deltaTime)
        {
            foreach (Entity e in getApplicableEntities())
            {
                PushableComponent pushComp = ( PushableComponent )e.getComponent(GlobalVars.PUSHABLE_COMPONENT_NAME);

                if (!pushComp.dontSlow && !pushComp.wasPushedLastFrame)
                {
                    VelocityComponent velComp = ( VelocityComponent )e.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

                    if (Math.Abs(velComp.x) > slowRate)
                    {
                        if (velComp.x < 0)
                        {
                            velComp.x += slowRate;
                        }
                        else
                        {
                            velComp.x -= slowRate;
                        }
                    }
                    else if (velComp.x != 0)
                    {
                        velComp.x = 0;
                    }
                }

                if (pushComp.wasPushedLastFrame)
                {
                    pushComp.wasPushedLastFrame = false;
                }
            }
        }
Example #6
0
        public void Update(float deltaTime)
        {
            foreach (Entity entity in _entities)
            {
                PositionComponent positionComponent = (PositionComponent)entity.GetComponentOfType(typeof(PositionComponent));
                VelocityComponent velocityComponent = (VelocityComponent)entity.GetComponentOfType(typeof(VelocityComponent));

                positionComponent.position += velocityComponent.velocity * deltaTime;

                // Windows collision tweak
                if (positionComponent.position.X < 0)
                {
                    positionComponent.position.X = 0;
                    velocityComponent.velocity.X = 0;
                }
                if (positionComponent.position.Y < 0)
                {
                    positionComponent.position.Y = 0;
                    velocityComponent.velocity.Y = 0;
                }
                if (positionComponent.position.X > _gameEngine.GetDisplayWindow().GetForm().Width - 50)
                {
                    positionComponent.position.X = _gameEngine.GetDisplayWindow().GetForm().Width - 50;
                    velocityComponent.velocity.X = 0;
                }
                if (positionComponent.position.Y > _gameEngine.GetDisplayWindow().GetForm().Height - 50)
                {
                    positionComponent.position.X = _gameEngine.GetDisplayWindow().GetForm().Height - 50;
                    velocityComponent.velocity.Y = 0;
                }
                positionComponent.orientation += velocityComponent.angularVelocity * deltaTime;
            }
        }
Example #7
0
        public override void _Ready()
        {
            AddToGroup(GROUP);
            _moveStateMachine.AddState(MoveState.GROUNDED, MoveStateGrounded);
            _moveStateMachine.AddState(MoveState.AIRBORNE, MoveStateAirborne);
            _moveStateMachine.AddState(MoveState.DASH, MoveStateDash);
            _moveStateMachine.AddState(MoveState.SLIDE, MoveStateSlide);
            _moveStateMachine.AddState(MoveState.WALL, MoveStateWall);
            _moveStateMachine.AddLeaveState(MoveState.WALL, LeaveMoveStateWall);
            _moveStateMachine.AddLeaveState(MoveState.GROUNDED, LeaveMoveStateGrounded);
            _moveStateMachine.AddLeaveState(MoveState.AIRBORNE, LeaveMoveStateAirborne);
            _moveStateMachine.AddLeaveState(MoveState.DASH, LeaveMoveStateDash);
            _moveStateMachine.SetInitialState(MoveState.GROUNDED);
            _animatedSprite    = GetNode <AnimatedSprite>("AnimatedSprite");
            _velocityComponent = this.GetFirstNodeOfType <VelocityComponent>();
            _healthComponent   = this.GetFirstNodeOfType <HealthComponent>();
            _animationPlayer   = GetNode <AnimationPlayer>("AnimationPlayer");
            _flipSprite        = GetNode <Sprite>("FlipSprite");
            _flipTween         = GetNode <Tween>("FlipTween");
            _walkParticles     = GetNode <Particles2D>("WalkParticles");
            _dashParticles     = GetNode <Particles2D>("DashParticles");

            var weaponSocket = this.GetFirstNodeOfType <WeaponSocketComponent>();

            weaponSocket.EquipWeapon((GD.Load("res://scenes/GameObject/Combat/GrenadeLauncher.tscn") as PackedScene).Instance() as Weapon);
            weaponSocket = GetNode <WeaponSocketComponent>("WeaponSocketComponent2");
            weaponSocket.EquipWeapon((GD.Load("res://scenes/GameObject/Combat/PlayerWeapon.tscn") as PackedScene).Instance() as Weapon);

            _flipTween.Connect("tween_all_completed", this, nameof(OnFlipTweenCompleted));
            _healthComponent?.Connect(nameof(HealthComponent.HealthChanged), this, nameof(OnHealthChanged));
        }
Example #8
0
        //--------------------------HANDLE DIRECTION CHANGE--------------------------
        private void checkForDirectionChange(Entity e)
        {
            SmushComponent    smushComp = ( SmushComponent )e.getComponent(GlobalVars.SMUSH_COMPONENT_NAME);
            VelocityComponent velComp   = ( VelocityComponent )e.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

            float stopBuffer = 0.01f;

            if (smushComp.getFallSpeed().X != 0 && Math.Abs(velComp.x) < stopBuffer)
            {
                if (smushComp.isFalling())
                {
                    startLowerWait(e);
                }
                else if (smushComp.isRising())
                {
                    startUpperWait(e);
                }
            }
            if (smushComp.getFallSpeed().Y != 0 && Math.Abs(velComp.y) < stopBuffer)
            {
                if (smushComp.isFalling())
                {
                    startLowerWait(e);
                }
                else if (smushComp.isRising())
                {
                    startUpperWait(e);
                }
            }
        }
Example #9
0
        public void fireItem(Entity e, DirectionalComponent dir)
        {
            TimedShooterComponent timedShooterComp = ( TimedShooterComponent )e.getComponent(GlobalVars.TIMED_SHOOTER_COMPONENT_NAME);
            PositionComponent     posComp          = (PositionComponent)e.getComponent(GlobalVars.POSITION_COMPONENT_NAME);
            ShooterBullet         bullet           = new ShooterBullet(level, level.rand.Next(Int32.MinValue, Int32.MaxValue), posComp.x, posComp.y, dir.getDir(), timedShooterComp.state);
            VelocityComponent     bulletVel        = ( VelocityComponent )bullet.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

            float bulletSpeed = 160.0f;

            if (dir.isUp())
            {
                bulletVel.setVelocity(0, -bulletSpeed);
            }
            else if (dir.isRight())
            {
                bulletVel.setVelocity(bulletSpeed, 0);
            }
            else if (dir.isDown())
            {
                bulletVel.setVelocity(0, bulletSpeed);
            }
            else if (dir.isLeft())
            {
                bulletVel.setVelocity(-bulletSpeed, 0);
            }
            level.addEntity(bullet);
        }
Example #10
0
        public void finishGrapple(Entity grapple)
        {
            if (!level.getPlayer().hasComponent(GlobalVars.PLAYER_INPUT_COMPONENT_NAME))
            {
                PlayerInputComponent plInComp = ( PlayerInputComponent )level.getPlayer().addComponent(new PlayerInputComponent(level.getPlayer()));
                plInComp.passedAirjumps = 0;
            }
            if (!level.getPlayer().hasComponent(GlobalVars.GRAVITY_COMPONENT_NAME))
            {
                level.getPlayer().addComponent(new GravityComponent(0, GlobalVars.STANDARD_GRAVITY));
            }


            if (stopPlayer)
            {
                VelocityComponent velComp = ( VelocityComponent )level.getPlayer().getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

                velComp.x = 0;
                velComp.y = 0;

                stopPlayer = false;
            }
            if (level.curGrap == grapple)
            {
                level.curGrap = null;
            }
            level.removeEntity(grapple);
            return;
        }
        public override void Update(float deltaTime)
        {
            if (!hasRunOnce)
            {
                level.getInputSystem().addKey(glideKey);

                //level.getInputSystem().addKey(blockSpawnKey);
                level.getInputSystem().addKey(speedyKey);

                level.getInputSystem().addKey(cycleDownPowerupKey);
                //level.getInputSystem().addKey(cycleUpPowerupKey);
                level.getInputSystem().addKey(equippedPowerupKey);

                level.getInputSystem().addKey(bounceKey);

                hasRunOnce = true;
            }
            if (glideActive)
            {
                VelocityComponent velComp = (VelocityComponent)this.level.getPlayer().getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);
                if (velComp.y > maxVelocity)
                {
                    velComp.setVelocity(velComp.x, maxVelocity);
                }
                glideTimer = glideTimer - deltaTime;
                if (glideTimer < 0.0f)
                {
                    GravityComponent gravComp = (GravityComponent)this.level.getPlayer().getComponent(GlobalVars.GRAVITY_COMPONENT_NAME);
                    gravComp.setGravity(gravComp.x, GlobalVars.STANDARD_GRAVITY);
                    glideActive = false;
                    glideTimer  = glideDuration;
                }
            }

            if (speedyTimer > 0)
            {
                if (level.getPlayer() == null)
                {
                    return;
                }
                speedyTimer -= deltaTime;
                if (!level.getPlayer().hasComponent(GlobalVars.VELOCITY_COMPONENT_NAME))
                {
                    return;
                }
                VelocityComponent velComp = (VelocityComponent)this.level.getPlayer().getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);
                if (speedyTimer <= 0 || Math.Abs(velComp.x) < GlobalVars.SPEEDY_SPEED)
                {
                    velComp.setVelocity(0, velComp.y);
                    speedyTimer  = -1;
                    speedyActive = false;
                    if (!level.getPlayer().hasComponent(GlobalVars.PLAYER_INPUT_COMPONENT_NAME))
                    {
                        level.getPlayer().addComponent(new PlayerInputComponent(level.getPlayer()));
                    }
                }
            }

            checkForInput();
        }
Example #12
0
        //Start Rising
        private void startRise(Entity e)
        {
            SmushComponent    smushComp = ( SmushComponent )e.getComponent(GlobalVars.SMUSH_COMPONENT_NAME);
            VelocityComponent velComp   = ( VelocityComponent )e.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

            startRise(velComp, smushComp);
        }
Example #13
0
        //--------------------------------------------------------------------------------



        //------------------------------------- Actions ----------------------------------
        public void playerJump(PositionComponent posComp, VelocityComponent velComp, PlayerInputComponent pelInComp)
        {
            //If it's landed on something, jump
            float checkY = posComp.y + (posComp.height / 2) + GlobalVars.MIN_TILE_SIZE / 2;

            //float buffer = 2;

            if (pelInComp.passedAirjumps < GlobalVars.numAirJumps)
            {
                velComp.setVelocity(velComp.x, pelInComp.jumpStrength);
                pelInComp.passedAirjumps++;
                pelInComp.justJumped = true;
            }

            /*
             * if ( level.getCollisionSystem().findObjectsBetweenPoints( posComp.x - posComp.width / 2 + buffer, checkY, posComp.x + posComp.width / 2 - buffer, checkY ).Count > 0 ) {
             *  velComp.setVelocity( velComp.x, pelInComp.jumpStrength );
             *  pelInComp.passedAirjumps = 0;
             * } else {
             *  if ( pelInComp.passedAirjumps < GlobalVars.numAirJumps ) {
             *      velComp.setVelocity( velComp.x, pelInComp.jumpStrength );
             *      pelInComp.passedAirjumps++;
             *  }
             * }
             * */
        }
Example #14
0
        public static Entity NewBasePlayer(String model, int gamePadIndex, Vector3 transformPos, Texture2D texture, String typeName)
        {
            Entity             player             = EntityFactory.NewEntity(typeName);
            TransformComponent transformComponent = new TransformComponent(player, transformPos);
            ModelComponent     modelComponent     = new ModelComponent(player, AssetManager.Instance.GetContent <Model>(model));
            VelocityComponent  velocityComponent  = new VelocityComponent(player);
            CollisionComponent collisionComponent = new CollisionComponent(player, new BoxVolume(EntityFactory.CreateBoundingBox(modelComponent.Model)));
            PlayerComponent    playerComponent    = new PlayerComponent(player);
            FrictionComponent  frictionComponent  = new FrictionComponent(player);
            TextureComponent   textureComponent   = new TextureComponent(player, texture);
            GravityComponent   gravityComponent   = new GravityComponent(player);
            EffectComponent    effectComponent    = new EffectComponent(player, AssetManager.Instance.GetContent <Effect>("Shading"));

            ComponentManager.Instance.AddComponentToEntity(player, modelComponent);
            ComponentManager.Instance.AddComponentToEntity(player, transformComponent);
            ComponentManager.Instance.AddComponentToEntity(player, velocityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, collisionComponent, typeof(CollisionComponent));
            ComponentManager.Instance.AddComponentToEntity(player, playerComponent);
            ComponentManager.Instance.AddComponentToEntity(player, frictionComponent);
            ComponentManager.Instance.AddComponentToEntity(player, textureComponent);
            ComponentManager.Instance.AddComponentToEntity(player, gravityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, effectComponent);

            TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            TransformHelper.SetBoundingBoxPos(collisionComponent, transformComponent);

            //TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            //TransformHelper.SetInitialBoundingSpherePos(collisionComponent, transformComponent);

            return(player);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="gameTime"></param>
        private void KeyBoardMove(int Id, GameTime gameTime)
        {
            KeyBoardComponent  kbc  = ComponentManager.Instance.GetEntityComponent <KeyBoardComponent>(Id);
            PositionComponent  p    = ComponentManager.Instance.GetEntityComponent <PositionComponent>(Id);
            PlayerComponent    pc   = ComponentManager.Instance.GetEntityComponent <PlayerComponent>(Id);
            VelocityComponent  v    = ComponentManager.Instance.GetEntityComponent <VelocityComponent>(Id);
            DirectionComponent dc   = ComponentManager.Instance.GetEntityComponent <DirectionComponent>(Id);
            JumpComponent      jump = ComponentManager.Instance.GetEntityComponent <JumpComponent>(Id);

            p.prevPosition = p.position;
            if (dc != null && v != null)
            {
                v.velocity.X = sideMovement * (int)dc.directio;
            }
            if (p != null && v != null && kbc != null && jump != null && dc != null)
            {
                if (kbc.state[ActionsEnum.Jump] == ButtonStates.Pressed && !pc.isFalling)
                {
                    if (dc.directio == Direction.Still)
                    {
                        dc.directio = dc.preDir;
                    }
                    if (v.velocity.Y > -jump.maxJumpHeight)
                    {
                        v.velocity.Y -= jump.jumpHeight;
                        ComponentManager.Instance.AddComponentToEntity(Id, new SoundEffectComponent("jump"));
                    }
                }
                v.velocity.Y += gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;
                p.position   += v.velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
        }
Example #16
0
    void IECSSystem.Execute(ECSEngine engine, ECSEntity[] entities)
    {
        for (int i = 0; i < entities.Length; i++)
        {
            ECSEntity entity = entities[i];

            PositionComponent pc = engine.GetComponent <PositionComponent>(entity);
            VelocityComponent vc = engine.GetComponent <VelocityComponent>(entity);

            if (Input.IsKeyPressed(KeyCode.W))
            {
                pc.Position.Y -= vc.Velocity.Y * Time.DeltaTime;
            }

            if (Input.IsKeyPressed(KeyCode.S))
            {
                pc.Position.Y += vc.Velocity.Y * Time.DeltaTime;
            }

            if (Input.IsKeyPressed(KeyCode.A))
            {
                pc.Position.X -= vc.Velocity.X * Time.DeltaTime;
            }

            if (Input.IsKeyPressed(KeyCode.D))
            {
                pc.Position.X += vc.Velocity.X * Time.DeltaTime;
            }

            engine.SetComponent <PositionComponent>(entity, pc);
        }
    }
        public void update(GameTime gameTime)
        {
            List <int> entitys = ComponentManager.Instance.GetAllEntitiesWithComponentType <HealthComponent>();

            if (entitys != null)
            {
                if (deathList.Count == 0)
                {
                    foreach (var en in entitys)
                    {
                        deathList.Add(en);
                    }
                }

                foreach (var entity in entitys)
                {
                    HealthComponent hc = ComponentManager.Instance.GetEntityComponent <HealthComponent>(entity);
                    if (hc.health <= 0 && !hc.isDead)
                    {
                        CollisionComponent cc = ComponentManager.Instance.GetEntityComponent <CollisionComponent>(entity);
                        ComponentManager.Instance.RemoveComponentFromEntity(entity, cc);
                        VelocityComponent vc = ComponentManager.Instance.GetEntityComponent <VelocityComponent>(entity);
                        ComponentManager.Instance.RemoveComponentFromEntity(entity, vc);
                        hc.isDead = true;
                        if (deathList.Count != 1)
                        {
                            deathList.Remove(entity);
                        }
                    }
                }
            }
        }
Example #18
0
        /// <summary>
        /// Check if networkinputcomponent's parameters are true and do actions on remote player
        /// </summary>
        /// <param name="gameTime"></param>
        /// <param name="playerEntity"></param>
        private void ParseNetworkInput(GameTime gameTime, Entity playerEntity)
        {
            NetworkInputComponent networkInputComponent = ComponentManager.Instance.ConcurrentGetComponentOfEntity <NetworkInputComponent>(playerEntity);
            VelocityComponent     velocityComponent     = ComponentManager.Instance.ConcurrentGetComponentOfEntity <VelocityComponent>(playerEntity);
            TransformComponent    transformComponent    = ComponentManager.Instance.ConcurrentGetComponentOfEntity <TransformComponent>(playerEntity);
            GravityComponent      gravityComponent      = ComponentManager.Instance.ConcurrentGetComponentOfEntity <GravityComponent>(playerEntity);

            if (networkInputComponent.MoveForward)
            {
                PlayerActions.AcceleratePlayerForwards(gameTime, velocityComponent);
            }
            if (networkInputComponent.MoveLeft)
            {
                PlayerActions.AcceleratePlayerLeftwards(gameTime, velocityComponent);
            }
            if (networkInputComponent.MoveRight)
            {
                PlayerActions.AcceleratePlayerRightwards(gameTime, velocityComponent);
            }
            if (networkInputComponent.Jump)
            {
                PlayerActions.PlayerJump(gameTime, velocityComponent);
            }
            if (networkInputComponent.MoveBackward)
            {
                PlayerActions.AcceleratePlayerBackwards(gameTime, velocityComponent);
            }
        }
Example #19
0
 public void endRightHorizontalMove(PositionComponent posComp, VelocityComponent velComp)
 {
     if (velComp.x > 0)
     {
         velComp.setVelocity(0, velComp.y);
     }
 }
Example #20
0
 public void endLowerMove(PositionComponent posComp, VelocityComponent velComp)
 {
     if (velComp.y > 0)
     {
         velComp.setVelocity(velComp.x, 0);
     }
 }
Example #21
0
 /// <summary>
 /// Accelerates the player backward until it reaches maximum running speed
 /// </summary>
 /// <param name="velocityComponent"></param>
 public static void AcceleratePlayerBackwards(GameTime gameTime, VelocityComponent velocityComponent)
 {
     if (velocityComponent.Velocity.Z > -playerMaxRunningSpeed)
     {
         velocityComponent.Velocity.Z = Math.Max(velocityComponent.Velocity.Z - playerForwardAcceleration, -playerForwardAcceleration);
     }
 }
Example #22
0
        //-----------------------------------------------------------------------------

        //----------------------------------- Input -----------------------------------
        public void checkForInput(PositionComponent posComp, VelocityComponent velComp, VisionInputComponent visInComp)
        {
            if (level.getInputSystem().myKeys[GlobalVars.KEY_JUMP].down)
            {
                beginMoveUp(posComp, velComp, visInComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_DOWN].down)
            {
                beginMoveDown(posComp, velComp, visInComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_LEFT].down)
            {
                beginMoveLeft(posComp, velComp, visInComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_RIGHT].down)
            {
                beginMoveRight(posComp, velComp, visInComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_JUMP].up)
            {
                endUpperMove(posComp, velComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_DOWN].up)
            {
                endLowerMove(posComp, velComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_RIGHT].up)
            {
                endRightHorizontalMove(posComp, velComp);
            }
            if (level.getInputSystem().myKeys[GlobalVars.KEY_LEFT].up)
            {
                endLeftHorizontalMove(posComp, velComp);
            }
        }
Example #23
0
        //Returns whether or not movement has been blocked by a collision
        public bool manageMovementColliderCheck(PositionComponent posComp, float newX, float newY, bool moveToContactH, bool moveToContactV)
        {
            VelocityComponent velComp = ( VelocityComponent )posComp.myEntity.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);

            //List of all collisions caused by potential move
            List <Entity> collisions = level.getCollisionSystem().checkForCollision(posComp.myEntity, newX, newY, posComp.width, posComp.height);

            bool movementBlocked = false;

            //Perform all collisions
            if (collisions.Count > 0 && !(level is CreationLevel))
            {
                foreach (Entity e in collisions)
                {
                    if (!(e.hasComponent(GlobalVars.COLLIDER_COMPONENT_NAME)))
                    {
                        continue;
                    }

                    //Handle the collision. handleCollision(...) will return true if it should stop the movement.
                    if (colHandler.handleCollision(posComp.myEntity, e))
                    {
                        movementBlocked = true;
                        stopMovementAfterCollision(e, posComp, velComp, newX, newY, moveToContactH, moveToContactV);
                    }
                }
            }
            return(movementBlocked);
        }
        /// <summary>
        /// Creates an new Player with Controlls
        /// </summary>
        /// <param name="pixlePer"> True if pixelPerfect shall be used </param>
        /// <param name="GamePade"> True if GamePad the player uses a gamepad </param>
        /// <param name="PadJump"> Key binding to gamePad </param>
        /// <param name="Jump"> key binding to keybord </param>
        /// <param name="position"> Player start Position </param>
        /// <param name="name"> The name off the player</param>
        /// <param name="dir"> The players starting direction</param>
        /// <param name="index">  Playerindex For GamePad </param>
        /// <returns></returns>
        public int CreatePlayer(bool pixlePer, bool GamePade, Buttons PadJump, Keys Jump, Vector2 position, string name, Direction dir, PlayerIndex index, Color colour)
        {
            SpriteEffects     flip;
            GamePadComponent  gam;
            KeyBoardComponent kcb;
            int id = ComponentManager.Instance.CreateID();

            if (dir == Direction.Left)
            {
                flip = SpriteEffects.FlipHorizontally;
            }
            else
            {
                flip = SpriteEffects.None;
            }

            if (GamePade == true)
            {
                gam = new GamePadComponent(index);
                gam.gamepadActions.Add(ActionsEnum.Jump, PadJump);
                ComponentManager.Instance.AddComponentToEntity(id, gam);
            }
            else
            {
                kcb = new KeyBoardComponent();
                kcb.keyBoardActions.Add(ActionsEnum.Jump, Jump);
                ComponentManager.Instance.AddComponentToEntity(id, kcb);
            }
            DirectionComponent          dc   = new DirectionComponent(dir);
            DrawableComponent           comp = new DrawableComponent(Game.Instance.GetContent <Texture2D>("Pic/kanin1"), flip);
            PositionComponent           pos  = new PositionComponent(position);
            VelocityComponent           vel  = new VelocityComponent(new Vector2(200F, 0), 50F);
            JumpComponent               jump = new JumpComponent(300F, 200F);
            CollisionRectangleComponent CRC  = new CollisionRectangleComponent(new Rectangle((int)pos.position.X, (int)pos.position.Y, comp.texture.Width, comp.texture.Height));
            CollisionComponent          CC   = new CollisionComponent(pixlePer);
            PlayerComponent             pc   = new PlayerComponent(name);
            DrawableTextComponent       dtc  = new DrawableTextComponent(name, Color.Black, Game.Instance.GetContent <SpriteFont>("Fonts/TestFont"));
            HUDComponent    hudc             = new HUDComponent(Game.Instance.GetContent <Texture2D>("Pic/PowerUp"), new Vector2(pos.position.X, pos.position.Y));
            HUDComponent    hudc2            = new HUDComponent(Game.Instance.GetContent <Texture2D>("Pic/PowerUp"), Vector2.One);
            HealthComponent hc = new HealthComponent(3, false);

            //AnimationComponent ani = new AnimationComponent(100, 114, comp.texture.Width, comp.texture.Height, 0.2);

            comp.colour = colour;

            ComponentManager.Instance.AddComponentToEntity(id, vel);
            ComponentManager.Instance.AddComponentToEntity(id, comp);
            ComponentManager.Instance.AddComponentToEntity(id, pos);
            ComponentManager.Instance.AddComponentToEntity(id, CRC);
            ComponentManager.Instance.AddComponentToEntity(id, CC);
            ComponentManager.Instance.AddComponentToEntity(id, pc);
            ComponentManager.Instance.AddComponentToEntity(id, dtc);
            ComponentManager.Instance.AddComponentToEntity(id, hudc);
            ComponentManager.Instance.AddComponentToEntity(id, hc);
            //ComponentManager.Instance.AddComponentToEntity(id, ani);
            ComponentManager.Instance.AddComponentToEntity(id, dc);
            ComponentManager.Instance.AddComponentToEntity(id, jump);
            return(id);
        }
Example #25
0
 public void stopRight(PositionComponent posComp, VelocityComponent velComp)
 {
     level.getMovementSystem().changeX(posComp, level.levelWidth - posComp.width / 2, true);
     if (velComp.x > 0)
     {
         velComp.setVelocity(0, velComp.y);
     }
 }
Example #26
0
        public override void Process(Entity entity)
        {
            ForceComponent    forceComponent    = entity.GetComponent <ForceComponent>();
            VelocityComponent velocityComponent = entity.GetComponent <VelocityComponent>();

            velocityComponent.Velocity += forceComponent.Force / forceComponent.Mass;
            forceComponent.Force        = Vector2.Zero;
        }
Example #27
0
        //Start Lower Waiting
        private void startLowerWait(Entity e)
        {
            SmushComponent    smushComp = ( SmushComponent )e.getComponent(GlobalVars.SMUSH_COMPONENT_NAME);
            VelocityComponent velComp   = ( VelocityComponent )e.getComponent(GlobalVars.VELOCITY_COMPONENT_NAME);
            TimerComponent    timerComp = ( TimerComponent )e.getComponent(GlobalVars.TIMER_COMPONENT_NAME);

            startLowerWait(velComp, smushComp, timerComp, e);
        }
Example #28
0
 public void stopDown(PositionComponent posComp, VelocityComponent velComp)
 {
     level.getMovementSystem().changeY(posComp, level.levelHeight - posComp.height / 2, true);
     if (velComp.y > 0)
     {
         velComp.setVelocity(velComp.x, 0);
     }
 }
Example #29
0
 /// <summary>
 /// Accelerates the player to the right until it reaches maximum strafeing speed
 /// </summary>
 /// <param name="velocityComponent"></param>
 public static void AcceleratePlayerRightwards(GameTime gameTime, VelocityComponent velocityComponent)
 {
     if (velocityComponent.Velocity.X > -playerMaxStrafeSpeed)
     {
         //velocityComponent.Velocity.X -= playerStrafeAcceleration * (float)gameTime.ElapsedGameTime.TotalSeconds;
         velocityComponent.Velocity.X = Math.Max(velocityComponent.Velocity.X - playerStrafeAcceleration, -playerStrafeAcceleration);
     }
 }
Example #30
0
 /// <summary>
 /// Accelerates the player forward until it reaches maximum running speed
 /// </summary>
 /// <param name="velocityComponent"></param>
 public static void AcceleratePlayerForwards(GameTime gameTime, VelocityComponent velocityComponent)
 {
     if (velocityComponent.Velocity.Z < playerMaxRunningSpeed)
     {
         //velocityComponent.Velocity.Z += playerForwardAcceleration * (float)gameTime.ElapsedGameTime.TotalSeconds;
         velocityComponent.Velocity.Z = Math.Min(velocityComponent.Velocity.Z + playerForwardAcceleration, playerForwardAcceleration);
     }
 }
    Vector2 getDesiredPosition(VelocityComponent velocity, PositionComponent position)
    {
        Vector2 positionOffset = velocity.vel;
        positionOffset *= -1.0f;
        positionOffset.Normalize();
        positionOffset *= LEADER_BEHIND_DIST;

        return position.pos + positionOffset;
    }
 Vector2 arrivalSteeringForce(PositionComponent position, VelocityComponent velocity, float speed, Vector2 desiredPosition, float slowingRadius)
 {
     Vector2 desiredVelocity = new Vector2((desiredPosition.x - position.pos.x), (desiredPosition.y - position.pos.y));
     float distance = desiredVelocity.magnitude;
     desiredVelocity.Normalize();
     desiredVelocity *= speed;
     if (distance < slowingRadius) {
         desiredVelocity *= (distance / slowingRadius);
     }
     return desiredVelocity - velocity.vel;
 }
Example #33
0
        public MoveAction(float expiration, int priority, Entity entity, Vector2 goal)
            : base(expiration, priority)
        {
            _entity = entity;
            _goal = goal;

            ComponentMapper<PositionComponent> positionMapper = new ComponentMapper<PositionComponent>(Director.SharedDirector.EntityWorld);
            _position = positionMapper.Get(entity);

            ComponentMapper<VelocityComponent> velocityMapper = new ComponentMapper<VelocityComponent>(Director.SharedDirector.EntityWorld);
            _velocity = velocityMapper.Get(entity);
        }
Example #34
0
        public static Manifold overlapAABB(Rectangle a, VelocityComponent velocityA, Rectangle b, VelocityComponent velocityB)
        {
            Manifold manifold = new Manifold();
            manifold.a = a;
            manifold.b = b;

            // vectrom from a to b
            Vector2 normal = new Vector2(b.X - a.X, b.Y - a.Y);

            //calculate half extents along x axis for each object
            float a_extent = (a.Width - a.X) / 2;
            float b_extent = (b.Width - b.X) / 2;

            //calculate overlap on x axis
            var x_overlap = a_extent + b_extent - Math.Abs(normal.X);

            // SAT test on x axis
            if (x_overlap > 0)
            {
                a_extent = (a.Height - a.X) / 2;
                b_extent = (b.Height - b.X) / 2;

                //calculate overlap on y axes
                var y_overlap = a_extent + b_extent - Math.Abs(normal.Y);

                // SAT test on y axis
                if (y_overlap > 0)
                {
                    // Find out which axis is axis of least penetration
                    if (x_overlap < y_overlap)
                    {
                        // point towards b knowing that dist points from a to b
                        if (normal.X < 0)
                        {
                            manifold.normal = new Vector2(-1, 0);
                        }
                        else
                        {
                            manifold.normal = new Vector2(1, 0);
                        }
                        manifold.penetration = x_overlap;
                        return manifold;
                    }
                    else
                    {
                        // Point toward B knowing that dist points from A to B
                        if (normal.Y < 0)
                        {
                            manifold.normal = new Vector2(0, -1);
                        }
                        else
                        {
                            manifold.normal = new Vector2(0, 1);
                        }
                        manifold.penetration = y_overlap;
                        return manifold;
                    }
                }
            }
            return new Manifold();
        }
Example #35
0
        public static void UpdateAABBPlayerCollision(PlayingState playingState)
        {
            IEnumerable<Guid> playerEntities = playingState.Entities.Where(x => (x.ComponentFlags & ComponentMasks.Player) == ComponentMasks.Player).Select(x => x.ID);
            IEnumerable<Guid> levelObjectEntities = playingState.Entities.Where(x => (x.ComponentFlags & ComponentMasks.LevelObjects) == ComponentMasks.LevelObjects).Select(x => x.ID);

            //create aa non velocity component for our level objects
            VelocityComponent levelObjectVelocityComponent = new VelocityComponent();
            levelObjectVelocityComponent.xVelocity = 0f;
            levelObjectVelocityComponent.yVelocity = 0f;

            foreach (Guid playerid in playerEntities)
            {
                AABBComponent playerAABBComponent = playingState.AABBComponents[playerid];
                VelocityComponent playerVelocityComponent = playingState.VelocityComponents[playerid];

                foreach (Guid lobjectid in levelObjectEntities)
                {
                    AABBComponent levelAABBComponent = playingState.AABBComponents[lobjectid];
                    Manifold manifold = overlapAABB(playerAABBComponent.BoundedBox, playerVelocityComponent, levelAABBComponent.BoundedBox, levelObjectVelocityComponent);
                    if (manifold.a != null)
                    {
                        resolveCollision(playerAABBComponent.BoundedBox, playerVelocityComponent, levelAABBComponent.BoundedBox, levelObjectVelocityComponent, manifold, playingState, playerid);
                    }

                }
            }

        }
Example #36
0
 void setVelocity(VelocityComponent velocity, PositionComponent actual, PositionComponent desired)
 {
     //velocity.x = (desired.x - actual.x) * 2.0f;
 }
Example #37
0
        public static void resolveCollision(Rectangle a, VelocityComponent velocityA, Rectangle b, VelocityComponent velocityB, Manifold m, PlayingState playingState, Guid aid, Guid? bid = null)
        {
            // calculate relative velocity
            Vector2 rv = new Vector2(velocityB.xVelocity - velocityA.xVelocity, velocityB.yVelocity - velocityA.yVelocity);

            //calculate relative velocity in terms of normal direction
            var velAlongNormal = DotProduct(rv, m.normal);

            //do not resolve if velocities are seperating
            if (velAlongNormal > 0)
            {
                return;
            }

            //calculate restitution
            var e = Math.Min(restitution, restitution);

            //calculate impulse scaler
            var j = -(1 + e) * velAlongNormal;
            j /= invmass + invmass;

            // Apply impulse
            Vector2 _impulse = new Vector2(m.normal.X * j, m.normal.Y * j);

            velocityA.xVelocity -= (invmass * _impulse.X);
            velocityA.yVelocity -= (invmass * _impulse.Y);

            velocityB.xVelocity += (invmass * _impulse.X);
            velocityB.yVelocity += (invmass * _impulse.Y);

            playingState.VelocityComponents[aid] = velocityA;

            if (bid != null)
            {
                playingState.VelocityComponents[(Guid)bid] = velocityB;
            }

            //float percent = .8f;
            //float slop = .01f;
            //var c = Math.Max(m.penetration - slop, 0) / (invmass + invmass) * percent * m.normal;
            //there is like some position shit that should go here but i dont know what
        }