Advertisement
saintshenanigans

movingobject

Apr 8th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.97 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4.  
  5.     //The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
  6.     public abstract class MovingObject : MonoBehaviour
  7.     {
  8.         public float moveTime = 0.01f;           //Time it will take object to move, in seconds.
  9.         public LayerMask blockingLayer;         //Layer on which collision will be checked.
  10.  
  11.  
  12.         private BoxCollider2D boxCollider;      //The BoxCollider2D component attached to this object.
  13.         private Rigidbody2D rb2D;               //The Rigidbody2D component attached to this object.
  14.         private float inverseMoveTime;          //Used to make movement more efficient.
  15.  
  16.  
  17.         //Protected, virtual functions can be overridden by inheriting classes.
  18.         protected virtual void Start ()
  19.         {
  20.             //Get a component reference to this object's BoxCollider2D
  21.             boxCollider = GetComponent <BoxCollider2D> ();
  22.  
  23.             //Get a component reference to this object's Rigidbody2D
  24.             rb2D = GetComponent <Rigidbody2D> ();
  25.  
  26.             //By storing the reciprocal of the move time we can use it by multiplying instead of dividing, this is more efficient.
  27.             inverseMoveTime = 1f / moveTime;
  28.         }
  29.  
  30.  
  31.         //Move returns true if it is able to move and false if not.
  32.         //Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
  33.         protected bool Move (int xDir, int yDir, out RaycastHit2D hit)
  34.         {
  35.             //Store start position to move from, based on objects current transform position.
  36.             Vector2 start = transform.position;
  37.  
  38.             // Calculate end position based on the direction parameters passed in when calling Move.
  39.             Vector2 end = start + new Vector2 (xDir, yDir);
  40.  
  41.             //Disable the boxCollider so that linecast doesn't hit this object's own collider.
  42.             boxCollider.enabled = false;
  43.  
  44.             //Cast a line from start point to end point checking collision on blockingLayer.
  45.             hit = Physics2D.Linecast (start, end, blockingLayer);
  46.  
  47.             //Re-enable boxCollider after linecast
  48.             boxCollider.enabled = true;
  49.  
  50.             //Check if anything was hit
  51.             if(hit.transform == null)
  52.             {
  53.                 //If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
  54.                 StartCoroutine (SmoothMovement (end));
  55.  
  56.                 //Return true to say that Move was successful
  57.                 return true;
  58.             }
  59.  
  60.             //If something was hit, return false, Move was unsuccesful.
  61.             return false;
  62.         }
  63.  
  64.  
  65.         //Co-routine for moving units from one space to next, takes a parameter end to specify where to move to.
  66.         protected IEnumerator SmoothMovement (Vector3 end)
  67.         {
  68.             //Calculate the remaining distance to move based on the square magnitude of the difference between current position and end parameter.
  69.             //Square magnitude is used instead of magnitude because it's computationally cheaper.
  70.             float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
  71.  
  72.             //While that distance is greater than a very small amount (Epsilon, almost zero):
  73.             while(sqrRemainingDistance > float.Epsilon)
  74.             {
  75.                 //Find a new position proportionally closer to the end, based on the moveTime
  76.                 Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
  77.  
  78.                 //Call MovePosition on attached Rigidbody2D and move it to the calculated position.
  79.                 rb2D.MovePosition (newPostion);
  80.  
  81.                 //Recalculate the remaining distance after moving.
  82.                 sqrRemainingDistance = (transform.position - end).sqrMagnitude;
  83.  
  84.                 //Return and loop until sqrRemainingDistance is close enough to zero to end the function
  85.                 yield return null;
  86.             }
  87.         }
  88.  
  89.  
  90.         //The virtual keyword means AttemptMove can be overridden by inheriting classes using the override keyword.
  91.         //AttemptMove takes a generic parameter T to specify the type of component we expect our unit to interact with if blocked (Player for Enemies, Wall for Player).
  92.         protected virtual void AttemptMove <T> (int xDir, int yDir)
  93.             where T : Component
  94.         {
  95.             //Hit will store whatever our linecast hits when Move is called.
  96.             RaycastHit2D hit;
  97.  
  98.             //Set canMove to true if Move was successful, false if failed.
  99.             bool canMove = Move (xDir, yDir, out hit);
  100.  
  101.             //Check if nothing was hit by linecast
  102.             if(hit.transform == null)
  103.                 //If nothing was hit, return and don't execute further code.
  104.                 return;
  105.  
  106.             //Get a component reference to the component of type T attached to the object that was hit
  107.             T hitComponent = hit.transform.GetComponent <T> ();
  108.  
  109.             //If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
  110.             if(!canMove && hitComponent != null)
  111.  
  112.                 //Call the OnCantMove function and pass it hitComponent as a parameter.
  113.                 OnCantMove (hitComponent);
  114.         }
  115.  
  116.  
  117.         //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
  118.         //OnCantMove will be overriden by functions in the inheriting classes.
  119.         protected abstract void OnCantMove <T> (T component)
  120.             where T : Component;
  121.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement