Raycast2D doesn't work correctly on rotated object
So I have a simple script, it casts a ray from a point and upwards. I have a Debug.DrawRay that draws a ray from the start point and up, unless the ray hits something, in which case it will stop where the ray hit.
However, when the object (with a 2D capsule collider) that is obstructing the 2D raycast is rotated to a certain angle, the hit is not detected anywhere but the object's ends.
In case you don't understand what I mean, here is a demonstration
Here is my script:
LineRenderer lr;
Vector2 startPoint;
Vector2 endPoint;
void Awake ()
{
lr = GetComponent<LineRenderer> ();
startPoint = lr.GetPosition (0);
endPoint = lr.GetPosition (1);
}
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast (startPoint, endPoint - startPoint);
if (hit)
{
Debug.DrawRay (startPoint, hit.point - startPoint, Color.white);
}
else
{
Debug.DrawRay (startPoint, endPoint - startPoint, Color.white);
}
}
The start and end points are from a line renderer that I will use to actually show the ray in the game, and at the moment I am using it to set the start point and direction of the ray with two points.
Answer by bibbis · Aug 05, 2017 at 06:27 AM
I'm having the exact same issue but with Physics2D.Linecast!
I'm trying to learn how to use line casting between the enemies and the player to see if they are within shooting range.
I couldn't understand why the line was only able to hit the player when the player was in certain angles around the enemy.
Now I can see that it has to do with the rotation of the player - the rotation of the object being hit - just like in your example!
Yeah, I figured out that certain types of colliders work, while others don't. For instance, a capsule collider has all sorts of issues, but a polygon collider and a box collider seem to work fine. Also I think it's fixed the the 2017 Unity beta update thing, but I could be wrong. Anyway if it's not yet fixed I hope they fix it soon.
You're right! $$anonymous$$y player uses a capsule collider to bumb into walls etc. So what I did to fix this was to add a smaller box collider inside the capsule. Now the player can be hit from all directions regardless of rotation!