- Home /
How do I add force to a RigidBody2D?
So I have this scene, where I have a player that can shoot bullets at an enemy. I want to AddForce to the RigidBody2D of the enemy when the bullet hits, but until now I have no success. My bullet script:
void Update()
{
theRB.velocity = transform.right * speed;
}
private void OnTriggerEnter2D(Collider2D other)
{
Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(gameObject);
if (other.tag == "Enemy")
{
other.GetComponent<EnemyHealthController>().DamageEnemy(damageToGive);
}
}
Where do I put the Addforce function? Do I have to get a reference from the enemy RigidBody on my Bullet Script? I'm kinda new to unity so any help is much appreciated! Thanks in advance. PS: I'm trying to make to a topdown shooter game.
Answer by LeFlop2001 · Jan 30, 2020 at 10:00 PM
Adding impactforce on collision is part of the unity engine so you won't have to script anything. But since you're using the OnTrigger function im assuming that either the enemy or the bullet is a trigger in which case there won't be a collision. you can simply use the OnCollision function instead
private void OnTriggerEnter2D(Collider2D other) {
Instantiate(impactEffect, transform.position, transform.rotation);
Destroy(gameObject);
if (other.tag == "Enemy")
{
Vector3 bulletDir = this.gameObject.transform.right;
other.GetComponent<EnemyHealthController>().DamageEnemy(damageToGive);
other.GetComponent<Rigidbody2D>().AddForce(bulletDir.normalized * bullet$$anonymous$$nockback, Force$$anonymous$$ode2D.Impulse);
}
}
I got it to work with this bit of code! Thanks!
Answer by logicandchaos · Jan 31, 2020 at 03:06 AM
other is your enemy reference. So to add force to it it would right after line 13, you would add other.GetComponant().AddForce(theRB.velocity); to add the force of the bullet to the enemy.
Your answer
Follow this Question
Related Questions
OnTriggerEnter2D(Collider2D other) 2 Answers
Way to achieve 3 lane mechanism in a 2D game 0 Answers
Adding force to mouse position adds force relative to screen center 0 Answers
Does anyone know how to fix this unity 2d movement isssue? X axis movement not working 0 Answers
Add Force if GameObject is detected in a Polygon Collider 2D 1 Answer