- Home /
Knockback effect in 2D.
Hello Game Developers! I intend to knock the player back as soon as it enters a trigger. I have the code right here.
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
// float dist = Vector2.Distance(col.gameObject.transform.position, this.transform.position);
Vector2 dir = col.transform.position - transform.position;
Vector2 force = dir.normalized * knockbackForce * Time.fixedDeltaTime;
Debug.DrawRay(transform.position, force, Color.red, 3);
print(force);
col.gameObject.GetComponent<Rigidbody2D>().AddForce(force,ForceMode2D.Impulse);
}
}
This script is attached to the object which causes the knock-back. The aforementioned object is supposed to knock the player back in the direction of the player relative to the object. Debug.Drawray displays a ray in the exact direction but the player doesn't respond whatsoever. The player has the appropriate tag assigned to it. Any help will be greatly appreciated.
Answer by I_Am_Err00r · Aug 22, 2019 at 04:01 PM
I don't have access to Unity and don't know enough about Rigidbody component to definitively give you a "this is what's going on" response, but have you tried increasing the knockbackForce to a ridiculous amount to see it affects the player? The code looks good, and if it is giving you the DrawRay is correct, then it sounds like the logic is flowing correctly and it might be the object just needs more knockbackForce.
I tried cranking up the force. Now the player gets knocked back only in the Y direction.