diff --git a/Tiles/Game.cs b/Tiles/Game.cs index a368e60..4184842 100644 --- a/Tiles/Game.cs +++ b/Tiles/Game.cs @@ -46,7 +46,7 @@ public class Game Player = new Player("Player") { - Position = World.GetGlobalPositionFromGrid(500, 500) + Position = World.GetGlobalPositionFromGrid(500, 200) }; CameraController = new CameraController(); diff --git a/Tiles/Player.cs b/Tiles/Player.cs index 8cbdede..96d56d4 100644 --- a/Tiles/Player.cs +++ b/Tiles/Player.cs @@ -10,8 +10,9 @@ public class Player public Vector2 Position { get; set; } public float Speed { get; set; } = 2f; public Texture2D Texture { get; private set; } - public Vector2 PointerPosition { get; private set; } + public bool IsColliding { get; private set; } = false; + public bool IsOnGround { get; private set; } private readonly string _imagePath; @@ -25,6 +26,8 @@ public class Player private Rectangle _currentRect; + private Vector2 _newPosition = Vector2.Zero; + public Player(string name, int id = 0, string imagePath = "data/core/player/dude.png") { Name = name; @@ -57,24 +60,33 @@ public class Player private void HandleInput() { + _newPosition = Position; + // WASD - if (Raylib.IsKeyDown(KeyboardKey.W)) Position += new Vector2(0, -1) * Speed; + if (Raylib.IsKeyDown(KeyboardKey.W)) _newPosition += new Vector2(0, -1) * Speed; if (Raylib.IsKeyDown(KeyboardKey.A)) { - Position += new Vector2(-1, 0) * Speed; + _newPosition += new Vector2(-1, 0) * Speed; _direction = 0; } - if (Raylib.IsKeyDown(KeyboardKey.S)) Position += new Vector2(0, 1) * Speed; + if (Raylib.IsKeyDown(KeyboardKey.S)) _newPosition += new Vector2(0, 1) * Speed; if (Raylib.IsKeyDown(KeyboardKey.D)) { - Position += new Vector2(1, 0) * Speed; + _newPosition += new Vector2(1, 0) * Speed; _direction = 1; } - + + HandleCollision(_newPosition); + + if (!IsColliding) + { + Position = _newPosition; + } + // Speed control if (Raylib.IsKeyReleased(KeyboardKey.Up)) Speed += 1f; if (Raylib.IsKeyReleased(KeyboardKey.Down)) Speed -= 1f; - + // Select tiles if (Raylib.IsKeyReleased(KeyboardKey.Right)) { @@ -118,4 +130,29 @@ public class Player Raylib.DrawRectangle((int)PointerPosition.X*Game.Instance.World.TileSize, (int)PointerPosition.Y*Game.Instance.World.TileSize, Game.Instance.World.TileSize, Game.Instance.World.TileSize, new Color(255, 255, 0, 80)); } + + private void HandleCollision(Vector2 newPosition) + { + var gridPos = Game.Instance.World.GetGridPositionFromGlobalPosition((int)newPosition.X, (int)newPosition.Y); + int tileSize = Game.Instance.World.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; + + for (int x = startX; x <= endX; x++) + { + for (int y = startY; y <= endY; y++) + { + if (Game.Instance.World.GetTile(x, y) != 0) + { + IsColliding = true; + return; + } + } + } + } } \ No newline at end of file