Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BounceProjectile : MonoBehaviour
- {
- public LayerMask BounceLayerMask;
- protected Projectile _projectile;
- protected SpriteRenderer _spriteRenderer;
- protected bool _isFlippedInitially;
- protected bool _hasFlipped;
- protected virtual void Awake()
- {
- _projectile = GetComponent<Projectile>();
- _spriteRenderer = GetComponent<SpriteRenderer>();
- }
- protected virtual void Bounce(Collider2D collision)
- {
- Vector3 rayStartPoint = transform.position - _projectile.Direction * 1.5f;
- RaycastHit2D[] hits = Physics2D.RaycastAll(rayStartPoint, _projectile.Direction, 10f, BounceLayerMask);
- foreach (RaycastHit2D hit in hits)
- {
- if (hit.collider.gameObject == collision.gameObject)
- {
- Debug.DrawRay(rayStartPoint, hit.normal, Color.blue);
- Debug.DrawRay(rayStartPoint, _projectile.Direction * 10f);
- Vector2 reflectDir = Vector2.Reflect(_projectile.Direction, hit.normal);
- float newRotationAngle = Mathf.Atan2(reflectDir.y, reflectDir.x) * Mathf.Rad2Deg;
- Quaternion newRotation = Quaternion.AngleAxis(newRotationAngle, Vector3.forward);
- if (_spriteRenderer != null)
- CheckFlip(_spriteRenderer.flipX);
- SetBounceDirection(reflectDir, newRotation);
- }
- }
- }
- private void CheckFlip(bool isSpriteFlipped)
- {
- if (isSpriteFlipped)
- {
- if (!_hasFlipped)
- {
- _spriteRenderer.flipX = !_spriteRenderer.flipX;
- _hasFlipped = true;
- }
- }
- }
- protected virtual void SetBounceDirection(Vector3 newDirection, Quaternion newRotation)
- {
- _projectile.Direction = newDirection;
- transform.rotation = newRotation;
- }
- private void OnTriggerEnter2D(Collider2D collision)
- {
- Bounce(collision);
- }
- private void OnEnable()
- {
- _hasFlipped = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement