Exemplo n.º 1
0
        private void UpdatePosition(Vector2 velocity, GameTime gameTime)
        {
            Vector2       newPositionX = Position + new Vector2(velocity.X, 0) * (float)gameTime.ElapsedGameTime.TotalSeconds;
            Vector2       newPositionY = Position + new Vector2(0, velocity.Y) * (float)gameTime.ElapsedGameTime.TotalSeconds;
            List <Entity> collidables  = world.GetCollidables(this);
            bool          moveX        = true;
            bool          moveY        = true;

            foreach (Entity e in collidables)
            {
                if (e != this)
                {
                    if (GetDrawRectangle(newPositionX).Intersects(e.GetDrawRectangle()))
                    {
                        moveX = false;
                        break;
                    }

                    if (GetDrawRectangle(newPositionY).Intersects(e.GetDrawRectangle()))
                    {
                        moveY = false;
                        break;
                    }
                }
            }

            if (moveX || moveY)
            {
                TileMap map = world.GetMap();

                int square = 3;
                int startY = Math.Max(square, (int)(Position.Y / Globals.TILE_SIZE));
                int startX = Math.Max(square, (int)(Position.X / Globals.TILE_SIZE));
                for (int y = startY - square; y < startY + square; y++)
                {
                    for (int x = startX - square; x < startX + square; x++)
                    {
                        if (map.GetLayer(1).GetTileAt(x, y) != 0)
                        {
                            Rectangle tileRect = new Rectangle(x * Globals.TILE_SIZE, y * Globals.TILE_SIZE, Globals.TILE_SIZE, Globals.TILE_SIZE);

                            if (GetDrawRectangle(newPositionX).Intersects(tileRect))
                            {
                                moveX = false;
                                break;
                            }

                            if (GetDrawRectangle(newPositionY).Intersects(tileRect))
                            {
                                moveY = false;
                                break;
                            }
                        }
                    }
                }
            }

            Vector2 newPosition = Position;

            if (moveX)
            {
                newPosition.X = newPositionX.X;
            }
            if (moveY)
            {
                newPosition.Y = newPositionY.Y;
            }

            Position = newPosition;
        }