Compare commits

...

1 Commits

Author SHA1 Message Date
6c9baf1da3 collision test 2024-11-21 09:59:20 -06:00

View File

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