diff --git a/Tiles/Player.cs b/Tiles/Player.cs index 8f65576..0d5c456 100644 --- a/Tiles/Player.cs +++ b/Tiles/Player.cs @@ -71,19 +71,22 @@ public class Player private void HandleInput() { _newPosition = Position; + IsColliding = false; // Reset collision flag before checking for new collisions // WASD - //if (Raylib.IsKeyDown(KeyboardKey.W)) _newPosition += new Vector2(0, -1) * Speed; if (Raylib.IsKeyDown(KeyboardKey.A)) { _newPosition += new Vector2(-1, 0) * Speed; _direction = 0; + HandleCollision(_newPosition); + if (!IsColliding) Position = _newPosition; } - //if (Raylib.IsKeyDown(KeyboardKey.S)) _newPosition += new Vector2(0, 1) * Speed; if (Raylib.IsKeyDown(KeyboardKey.D)) { _newPosition += new Vector2(1, 0) * Speed; _direction = 1; + HandleCollision(_newPosition); + if (!IsColliding) Position = _newPosition; } HandleGravity(); @@ -144,38 +147,23 @@ public class Player private void HandleCollision(Vector2 newPosition) { - var gridPos = Game.Instance.World.GetGridPositionFromGlobalPosition((int)newPosition.X, (int)newPosition.Y); int tileSize = Game.Instance.World.TileSize; + int gridX1 = (int)(newPosition.X / tileSize); + int gridY1 = (int)(newPosition.Y / tileSize); + int gridX2 = (int)((newPosition.X + _currentRect.Width) / tileSize); + int gridY2 = (int)((newPosition.Y + _currentRect.Height) / tileSize); - int startX = (int)gridPos.X; - int startY = (int)gridPos.Y; - int endX = (int)((newPosition.X + _currentRect.Width) / tileSize); - int endY = (int)((newPosition.Y + _currentRect.Height) / tileSize); - - IsColliding = false; - IsOnGround = false; - - for (int x = startX; x <= endX; x++) + // Check the tiles at the new position + if (Game.Instance.World.GetTile(gridX1, gridY1) != 0 || + Game.Instance.World.GetTile(gridX2, gridY1) != 0 || + Game.Instance.World.GetTile(gridX1, gridY2) != 0 || + Game.Instance.World.GetTile(gridX2, gridY2) != 0) { - for (int y = startY; y <= endY; y++) - { - if (Game.Instance.World.GetTile(x, y) != 0) - { - IsColliding = true; - return; - } - } + IsColliding = true; } - - // Check if player is on the ground - int groundY = endY + 1; - for (int x = startX; x <= endX; x++) + else { - if (Game.Instance.World.GetTile(x, groundY) != 0) - { - IsOnGround = true; - break; - } + IsColliding = false; } } } \ No newline at end of file