- Home /
Knockback in 2d shooter
Hello,
I'm trying to apply a knockback effect to enemies when they are hit by a bullet. I have the basics, but it's not working exactly as intended.
Here's the current code:
// Get vector between bullet and enemy & zero the Y
Vector3 bulletDir = Other.transform.position - transform.position;
bulletDir.y = 0;
// Apply force along the normalised vector
float force = 1000;
Other.rigidbody.AddForce(bulletDir.normalized * force);
If the enemy is hit on the centre, it knocks them back in the direction the bullet was travelling, but if it hits on either of the sides, it knocks them to the side. I'd like for the enemy to always be knocked back in the direction of the bullet. Suggestions greatly appreciated & thanks for reading!
Answer by DMCH · Feb 25, 2013 at 11:50 PM
Figured it out. Posting answer incase it's useful to someone else. You need the current direction of the bullet which you can get from transform.forward.
Vector3 bulletDir = this.gameObject.transform.forward;
bulletDir.y = 0;
float force = 1000;
Other.rigidbody.AddForce(bulletDir.normalized * force);
Where do you put this code? I have a PistolScript, a NPCLogicScript, and a HealthScript for the NPC. Where should I implement this function?
I put it in the script attached to the bullet. Sounds like you might be using raycasting to detect hits, so you probably should apply force to the NPC along the player's current rotation.
Thanks man! $$anonymous$$ore people should do like this when they find a solution