Advertisement
Guest User

Dodgy collision detection

a guest
Jan 26th, 2015
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. private void HandleCollisions()
  2.         {
  3.             var gridX = Mathf.Floor(_player.x / TileWidth);
  4.             var gridY = Mathf.Floor(_player.y / TileHeight);
  5.  
  6.             for (var x = gridX - 1; x <= gridX + 1; x++)
  7.             {
  8.                 for (var y = gridY - 1; y <= gridY + 1; y++)
  9.                 {
  10.                     if (_tiles[(int)x, (int)y] != null)
  11.                     {
  12.                         var tile = _tiles[(int)x, (int)y];
  13.                         var tileRect = tile.localRect.CloneAndOffset(tile.x, tile.y);
  14.                         var playerRect = _player.localRect.CloneAndOffset(_player.x, _player.y);
  15.  
  16.                         if (tileRect.CheckIntersect(playerRect))
  17.                         {
  18.                             //tile.color = new Color(255, 0, 0);
  19.                             CalculateDepth(playerRect, tileRect);
  20.                         }
  21.                         else
  22.                         {
  23.                             // If we're not colliding with anything at all, I guess we're in the air.
  24.                             _player.OnGround = false;
  25.                         }
  26.                     }
  27.                 }
  28.             }
  29.         }
  30.  
  31.         private void CalculateDepth(Rect a, Rect b)
  32.         {
  33.             var distX = a.x - b.x;
  34.             var distY = a.y - b.y;
  35.             var minDistX = (a.width / 2) + (b.width / 2);
  36.             var minDistY = (a.height / 2) + (b.height / 2);
  37.             var depthX = distX > 0 ? minDistX - distX : -minDistX - distX; // Calculate intersection depth.
  38.             var depthY = distY > 0 ? minDistY - distY : -minDistY - distY;
  39.  
  40.             if (Mathf.Abs(depthX) > Mathf.Abs(depthY)) // Resolve along axis with smallest intersection depth.
  41.             {
  42.                 if (depthY > 0) // We're hitting the top of a tile.
  43.                 {
  44.                     _player.OnGround = true;
  45.                     _player.Jumping = false;
  46.                 }
  47.                 else // Otherwise we hit our head and need to come back down.
  48.                 {
  49.                     _player.YSpeed = 0;
  50.                 }
  51.  
  52.                 _player.y += depthY;
  53.             }
  54.             else
  55.             {
  56.                 _player.x += depthX;
  57.             }
  58.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement