Hi, I’m quite new to this Unity thing and I need to solve this problem for my 2D project. So basically i have a script, where enemy follows the player. I need enemy to knockback the player if player stays too close to enemy for lets say 1 second. I’m using Rigidbodies and Box colliders. I tried using Addforce but didnt quite seem to work. Any ideas how i might get this done? This is my code currently. Thanks for your help!!
You’re probably better off using “void OnTriggerEnter2D(Collider2D coll)”
(However if you need your BoxCollider2D to not be a Trigger then you may need to put another BoxCollider2D on an empty child GameObject)
Make sure in the Inspector->BoxCollider2D->IsTrigger is selected
Create a variable of type float named forceAmount and set it to something above zero.
Create a variable of type float named knockbackDelay and set it to the seconds you want the delay to be.
Create a variable of Rigidbody2D named rb and like how you have gotten the transform of the player, instead get the Rigidbody2D
But you also wanted a time delay on the knockback so I think you would need an IEnumerator to do this properly. If you haven’t used one before don’t stress, the one you’ll use is pretty straightforward.
This code hasn’t been tested but see how it goes:
public float speed;
private Transform target;
private float someScale;
// Amount of "kick" the force has
public float forceAmount;
// Time to wait until the knockback occurs
public float knockbackDelay;
// Rigidbody2D variable to hold the player Rigidbody2D
private Rigidbody2D rb;
// Use this for initialization
void Start()
{
someScale = transform.localScale.x;
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
rb = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(transform.position, target.position) > 1.8)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
// Your other stuff in here about turning
// ...
// ... etc.
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
// Call coroutine to wait for the set amount of time
StartCoroutine(WaitForKnockback(knockbackDelay));
// This adds a force to the PLAYER in the "forward" direction of THIS gameobject
// This assumes the rotation of this gameobject is facing the player
rb.AddForce(transform.right * forceAmount, ForceMode2D.Impulse);
}
}
// Waits for the amount of time passed in as a parameter
IEnumerator WaitForKnockback(float time)
{
yield return new WaitForSeconds(time);
}