Advertisement
jwow22

Collisions

Jan 4th, 2022
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. public class Collisions : MonoBehaviour
  2. {
  3.     [SerializeField] public bool enableCollisions;
  4.    
  5.     // Handling collisions
  6.     private Body headBody;
  7.     private Snake _snake;
  8.     private SnakeSlicing _snakeSlicing;
  9.    
  10.     // Handling collision behaviour
  11.     private Spawner _spawner;
  12.    
  13.     private void OnCollision(GridObject otherGridObject)
  14.     {
  15.         // Loot collision
  16.         if (otherGridObject.objectType == ObjectType.Loot)
  17.         {
  18.             otherGridObject.OnPickup(_snake);
  19.             _spawner.DestroyObject(otherGridObject);
  20.             return;
  21.         }
  22.  
  23.         // Body collision
  24.         if (otherGridObject.objectType == ObjectType.Body)
  25.         {
  26.             // Simple collision
  27.             if (!_snakeSlicing.enabled || _snakeSlicing == null)
  28.             {
  29.                 _snake.DestroySelf();
  30.                 return;
  31.             }
  32.             // Sliced collision
  33.             Body otherBody = otherGridObject.GetComponent<Body>();
  34.             _snakeSlicing.Slice(otherBody);
  35.         }
  36.     }
  37.    
  38.     public void CheckCollision()
  39.     {
  40.         if (!enableCollisions) { return; }
  41.        
  42.         headBody = _snake.bodyParts[0];
  43.         if (headBody.gridObject.currentTile.currentObjects.Count > 1)
  44.         {
  45.             GridObject otherGridObject = FindOtherGridObject();
  46.  
  47.             // No collision
  48.             if (otherGridObject == null) { return; }
  49.            
  50.             // Collision happened
  51.             OnCollision(otherGridObject);
  52.         }
  53.     }
  54.  
  55.     private GridObject FindOtherGridObject()
  56.     {
  57.         foreach (GridObject gridObject in headBody.gridObject.currentTile.currentObjects)
  58.         {
  59.             if (gridObject != headBody.gridObject && gridObject.enableCollision)
  60.             {
  61.                 return gridObject;
  62.             }
  63.         }
  64.         return null;
  65.     }
  66.  
  67.     private void Awake()
  68.     {
  69.         _snake = GetComponent<Snake>();
  70.         _snakeSlicing = GetComponent<SnakeSlicing>();
  71.        
  72.         _spawner = FindObjectOfType<Spawner>();
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement