using System.Collections; using System.Collections.Generic; using UnityEngine; public class Knockback : MonoBehaviour { public bool GettingKnockedBack { get; private set; } // Indicates whether the object is currently experiencing knockback [SerializeField] private float knockBackTime = .2f; // Duration of knockback effect private Rigidbody2D rb; // Reference to the Rigidbody2D component private void Awake() { rb = GetComponent(); // Initialize the Rigidbody2D reference } // Applies knockback force to the object public void GetKnockedBack(Transform damageSource, float knockBackThrust) { GettingKnockedBack = true; // Set the knockback status to true Vector2 difference = (transform.position - damageSource.position).normalized * knockBackThrust * rb.mass; rb.AddForce(difference, ForceMode2D.Impulse); // Apply the knockback force as an impulse StartCoroutine(KnockRoutine()); // Start the knockback routine } // Handles the duration of the knockback effect private IEnumerator KnockRoutine() { yield return new WaitForSeconds(knockBackTime); // Wait for the knockback duration rb.velocity = Vector2.zero; // Stop any ongoing movement GettingKnockedBack = false; // Reset the knockback status } }