Advertisement
ChrisTutorials

Attack.cs for Platformer Project

Mar 18th, 2023
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Attack : MonoBehaviour
  4. {
  5.     public int baseDamage = 10;
  6.     public Vector2 knockback = Vector2.zero;
  7.  
  8.     Collider2D hitCollider;
  9.  
  10.     private void Awake()
  11.     {
  12.         hitCollider = GetComponent<Collider2D>();
  13.         hitCollider.enabled = false;
  14.     }
  15.  
  16.     private void Start()
  17.     {
  18.         // Prevent accidental hits before attack enables collider
  19.         hitCollider.enabled = false;
  20.     }
  21.  
  22.     /// <summary>
  23.     /// When the attack collider connects with a damageable character,
  24.     /// call the hit function on the damageable to handle incoming damage and force knockback
  25.     /// </summary>
  26.     /// <param name="collision"></param>
  27.     private void OnTriggerEnter2D(Collider2D collision)
  28.     {
  29.         Damageable damageable = collision.GetComponent<Damageable>();
  30.  
  31.         if (damageable != null)
  32.         {
  33.             // Can hit and deal damage so deal damage
  34.             int adjustedDamage = Mathf.RoundToInt(baseDamage);
  35.  
  36.             // Flip knockback depending on hit direction
  37.             Vector2 directionToTarget = (collision.transform.position - transform.position).normalized;
  38.             float xSign = Mathf.Sign(directionToTarget.x);
  39.             Vector2 finalKnockback = new Vector2(knockback.x * xSign, knockback.y);
  40.  
  41.             damageable.Hit(adjustedDamage, finalKnockback);
  42.         }
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement