Example #1
0
        /// <summary>
        /// Player's update movement
        /// </summary>
        /// <param name="input"><see cref="InputService"/></param>
        /// <param name="config"><see cref="ConfigurationService"/></param>
        /// <param name="time"><see cref="GameTime"/></param>
        /// <param name="level"><see cref="Level"/></param>
        public void Update(InputService input, ConfigurationService config, GameTime time, Level level)
        {
            OldX = X;
            OldY = Y;

            VelocityX = 0;
            VelocityY = 0;

            if (input.IsKeyPressed(config.KEY_MoveUp))
            {
                VelocityY = -Speed * (float)time.ElapsedGameTime.TotalSeconds;
            }
            if (input.IsKeyPressed(config.KEY_MoveDown))
            {
                VelocityY = Speed * (float)time.ElapsedGameTime.TotalSeconds;
            }
            if (input.IsKeyPressed(config.KEY_MoveLeft))
            {
                VelocityX = -Speed * (float)time.ElapsedGameTime.TotalSeconds;
            }
            if (input.IsKeyPressed(config.KEY_MoveRight))
            {
                VelocityX = Speed * (float)time.ElapsedGameTime.TotalSeconds;
            }

            X += VelocityX;
            Y += VelocityY;

            // Collision detection on move
            bool horizontalCollision = false;
            bool verticalCollision   = false;

            UtilsHelper.Loops(3, 3, (x, y) => {
                int posx = OnMapX - 1 + x;
                int posy = OnMapY - 1 + y;

                if (posx < 0 || posy < 0 || posx >= level.Width || posy >= level.Height || !level.Map[posy * level.Width + posx].IsWall)
                {
                    return;
                }

                CollisionType collision = UtilsHelper.CheckCollision(this, level.Map[posy * level.Width + posx]);

                if (!horizontalCollision && (collision == CollisionType.Left || collision == CollisionType.Right))
                {
                    horizontalCollision = true;
                    X = OldX;
                }

                if (!verticalCollision && (collision == CollisionType.Top || collision == CollisionType.Bottom))
                {
                    verticalCollision = true;
                    Y = OldY;
                }
            });
        }