- Home /
Calculating angle using a raycastHit2D
I am crating a physics2d.linecast and storing the result in a raycastHit2D:
targetCast = Physics2D.Linecast (transform.position, Camera.main.ScreenToWorldPoint (Input.mousePosition), 1 << 8);
I would then like to calculate the angle between the point from which the linecast was fired (transform.position), and the surface of the collider that the linecast collided with.
The only way that I can think of to do this is to fire a second linecast at a slightly different angle, yet still hitting the collider, and then use the positions of the two raycastHit2D objects, in combination with cosine law, in order to calculate the angle between the surface of the collider and the point from the linecast is fired.
I am simply wishing to know whether or not this is the correct way to do this, or if unity has provided a way, or even if there is a better approach.
This is a 2D project written in C#.
I understand that this may not be the easiest to follow, so if you have any questions, please do not hesitate to ask.
Answer by robertbu · Aug 18, 2014 at 12:52 AM
A RaycastHit returns a normal. So one vector is from the hit point back to the cast point. The second vector is the normal. Calculate the unsigned angle between the two and subtract it from 90 degrees:
var mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition)
targetCast = Physics2D.Linecast (transform.position, mousePos, 1 << 8);
if (targetCast.collider != null) {
var angle = Vector2.Angle(transform.position - mousePos, targetCast.normal);
angle = 90.0 - Mathf.Abs(angle);
Debug.Log("Angle from surface = " + angle);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613160836im_/https://answers.unity.com/themes/thub/images/avi.jpg)