Advertisement
AdobeWallHacks

Untitled

Jul 3rd, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public abstract class MovingObject : MonoBehaviour {
  6.  
  7.     public float moveTime = 0.1f;
  8.     public LayerMask blockingLayer;
  9.  
  10.     private BoxCollider2D boxCollider;
  11.     private Rigidbody2D rb2D;
  12.     private float inverseMoveTime;
  13.  
  14.     // Use this for initialization
  15.     protected virtual void Start()
  16.     {
  17.         boxCollider = GetComponent<BoxCollider2D>();
  18.         rb2D = GetComponent<Rigidbody2D>();
  19.         inverseMoveTime = 1f / moveTime;
  20.     }
  21.  
  22.     protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
  23.     {
  24.         Vector2 start = transform.position;
  25.         Vector2 end = start + new Vector2(xDir, yDir);
  26.  
  27.         boxCollider.enabled = false;
  28.         hit = Physics2D.Linecast(start, end, blockingLayer);
  29.         boxCollider.enabled = true;
  30.  
  31.         if (hit.transform == null)
  32.         {
  33.             StartCoroutine(SmoothMovement(end));
  34.             return true;
  35.         }
  36.  
  37.         return false;
  38.  
  39.     }
  40.  
  41.     protected IEnumerator SmoothMovement(Vector3 end)
  42.     {
  43.         float sqrRemainDistance = (transform.position - end).sqrMagnitude;
  44.  
  45.         while (sqrRemainDistance > float.Epsilon)
  46.         {
  47.             Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
  48.             rb2D.MovePosition(newPostion);
  49.             sqrRemainDistance = (transform.position - end).sqrMagnitude;
  50.             yield return null;
  51.         }
  52.     }
  53.  
  54.     protected virtual AttemptMove<T>(int xDir, int yDir)
  55.       where T : Component;
  56.     {
  57.         RaycastHit2D hit;
  58.         bool canMove = Move(xDir, yDir, out hit);
  59.  
  60.         if (hit.transform == null)
  61.         {
  62.             return;
  63.         }
  64.  
  65.         T hitComponent = hit.transform.GetComponent<T>();
  66.        
  67.         if (!canMove && hitComponent != null)
  68.         {
  69.             OnCantMove(hitComponent);
  70.         }
  71.     }
  72.  
  73.     protected abstract void OnCantMove<T>(T Component)
  74.         where T : Component;
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement