- Home /
Adding force to object hit by sword
Hi, I have an overhead fantasy game in 2D, where the character swings a sword through an arc. I have implemented things with basic colliders and rigidbody2d's, but the results are a little anemic.
I wanted to add force to the hit through script so enemies go flying just a little further. However, my code is producing strange results, where enemies go flying in weird directions. For instance, I hit the enemy with a sword moving through a counter-clockwise arc, and the enemy shoots off to the right - almost the opposite of what I'd expect.
Can anyone see what might be wrong with this code?
void OnCollisionEnter2D(Collision2D coll)
{
coll.rigidbody.AddForce(coll.contacts[0].normal.normalized * 500);
}
}
I believe I've solved it with some furious Googling and the following code:
void OnCollisionEnter2D(Collision2D coll)
{
Vector3 dir = coll.transform.position - transform.position;
coll.rigidbody.AddForce(dir.normalized * 500);
}
I want to know how you posted your comment before you question XD
haha, well I answered the question before it was approved by moderators. I guess the timestamp on the main question resets when it's approved, but not the followup.
Ah $$anonymous$$akes sense now lol. Glad you solved the problem.