- Home /
How to calculate angle between 2D objects and use the result?
Firstly I'm not new to Unity but I do struggle to learn code without having some clear examples to work from. I'm having a hard time deciphering how to use the code in the docs because they're not used in a context that I understand.
That being said, my problem is quite simple and I'm sue the answer is in the docs for contactpoints2d etc.
I'm firing a 2d object (a circle - bullet), at enemies (a collection of 2d boxes).
I want to detect the angle of impact from the bullet and then work out if the angle was too shallow for a penetration. If it was, the bullet simply bounces off. Just like in Company of Heroes.
I tried two vesions of the same code and each has it's own weirdness.
1 -
void OnCollisionEnter2D(Collision2D other){
Vector2 normal = other.contacts [0].normal;
Debug.Log(Vector2.Angle (other.gameObject.transform.position, -normal));
if (Vector2.Angle (other.gameObject.transform.position, -normal) < _maxAngle) {
//bullet bounces off
Debug.Log("bounce off");
} else {
//bullet penetrates
Debug.Log("Penetrates");
TakeDamage (other);
}
}
In this version the angle reported in the debug seems to be around 176 no matter where I shoot from, UNTIL I shoot from a very oblique angle - at which point it changes to around 70.
void OnCollisionEnter2D(Collision2D other){
Vector3 normal = other.contacts [0].normal;
Debug.Log(Vector3.Angle (other.gameObject.transform.position, -normal));
if (Vector3.Angle (other.gameObject.transform.position, -normal) < _maxAngle) {
//bullet bounces off
Debug.Log("bounce off");
} else {
//bullet penetrates
Debug.Log("Penetrates");
TakeDamage (other);
}
}
This is the original version I was using. The result of this one way promising when firing from the bottom of the screen upwards at a box2d. The angles seemed to be quite sensible and it seemeed to be mostly there. However, when I shot sideways at another box the angles were completely different to what I'd expect and it was useless.
It's worth noting that I was using 4 boxes as armour, arranged in a square, to represent the sides of a vehicle. They were child objects of a parent "enemy". They are just scaled boxes - maybe scaling them affects normal detection? I have also tried with the boxes pulled out to the root of the scene and it seemed to make no difference.
Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220612144806im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D Reflect(bounce) With Rotation 0 Answers
Finding the angle between 2 clicked points 2 Answers
PlayOneShot not playing sound 1 Answer
2D GunPivot Bug 1 Answer
Ball bounce problem 1 Answer