Advertisement
Malaussene

TDE - BounceProjectile

Jun 3rd, 2020
747
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. public class BounceProjectile : MonoBehaviour
  2.     {
  3.         public LayerMask BounceLayerMask;
  4.  
  5.         protected Projectile _projectile;
  6.         protected SpriteRenderer _spriteRenderer;
  7.         protected bool _isFlippedInitially;
  8.         protected bool _hasFlipped;
  9.  
  10.         protected virtual void Awake()
  11.         {
  12.             _projectile = GetComponent<Projectile>();
  13.             _spriteRenderer = GetComponent<SpriteRenderer>();
  14.         }
  15.  
  16.         protected virtual void Bounce(Collider2D collision)
  17.         {
  18.             Vector3 rayStartPoint = transform.position - _projectile.Direction * 1.5f;
  19.  
  20.             RaycastHit2D[] hits = Physics2D.RaycastAll(rayStartPoint, _projectile.Direction, 10f, BounceLayerMask);
  21.  
  22.             foreach (RaycastHit2D hit in hits)
  23.             {
  24.                 if (hit.collider.gameObject == collision.gameObject)
  25.                 {
  26.                     Debug.DrawRay(rayStartPoint, hit.normal, Color.blue);
  27.                     Debug.DrawRay(rayStartPoint, _projectile.Direction * 10f);
  28.                     Vector2 reflectDir = Vector2.Reflect(_projectile.Direction, hit.normal);
  29.                     float newRotationAngle = Mathf.Atan2(reflectDir.y, reflectDir.x) * Mathf.Rad2Deg;
  30.                     Quaternion newRotation = Quaternion.AngleAxis(newRotationAngle, Vector3.forward);
  31.                     if (_spriteRenderer != null)
  32.                         CheckFlip(_spriteRenderer.flipX);
  33.                     SetBounceDirection(reflectDir, newRotation);
  34.                 }
  35.             }
  36.         }
  37.  
  38.         private void CheckFlip(bool isSpriteFlipped)
  39.         {
  40.             if (isSpriteFlipped)
  41.             {
  42.                 if (!_hasFlipped)
  43.                 {
  44.                     _spriteRenderer.flipX = !_spriteRenderer.flipX;
  45.                     _hasFlipped = true;
  46.                 }
  47.             }
  48.  
  49.         }
  50.  
  51.         protected virtual void SetBounceDirection(Vector3 newDirection, Quaternion newRotation)
  52.         {
  53.             _projectile.Direction = newDirection;
  54.             transform.rotation = newRotation;
  55.         }
  56.  
  57.         private void OnTriggerEnter2D(Collider2D collision)
  58.         {
  59.             Bounce(collision);
  60.         }
  61.  
  62.         private void OnEnable()
  63.         {
  64.             _hasFlipped = false;
  65.         }
  66.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement