Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void HandleCollisions()
- {
- var gridX = Mathf.Floor(_player.x / TileWidth);
- var gridY = Mathf.Floor(_player.y / TileHeight);
- for (var x = gridX - 1; x <= gridX + 1; x++)
- {
- for (var y = gridY - 1; y <= gridY + 1; y++)
- {
- if (_tiles[(int)x, (int)y] != null)
- {
- var tile = _tiles[(int)x, (int)y];
- var tileRect = tile.localRect.CloneAndOffset(tile.x, tile.y);
- var playerRect = _player.localRect.CloneAndOffset(_player.x, _player.y);
- if (tileRect.CheckIntersect(playerRect))
- {
- //tile.color = new Color(255, 0, 0);
- CalculateDepth(playerRect, tileRect);
- }
- else
- {
- // If we're not colliding with anything at all, I guess we're in the air.
- _player.OnGround = false;
- }
- }
- }
- }
- }
- private void CalculateDepth(Rect a, Rect b)
- {
- var distX = a.x - b.x;
- var distY = a.y - b.y;
- var minDistX = (a.width / 2) + (b.width / 2);
- var minDistY = (a.height / 2) + (b.height / 2);
- var depthX = distX > 0 ? minDistX - distX : -minDistX - distX; // Calculate intersection depth.
- var depthY = distY > 0 ? minDistY - distY : -minDistY - distY;
- if (Mathf.Abs(depthX) > Mathf.Abs(depthY)) // Resolve along axis with smallest intersection depth.
- {
- if (depthY > 0) // We're hitting the top of a tile.
- {
- _player.OnGround = true;
- _player.Jumping = false;
- }
- else // Otherwise we hit our head and need to come back down.
- {
- _player.YSpeed = 0;
- }
- _player.y += depthY;
- }
- else
- {
- _player.x += depthX;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement