# Thread: line-square and circle-square intersections

1. ## line-square and circle-square intersections

Hi guys, im making a little simulator but I need to do two things - line of sight detection and collision detection.

What I have is a GDI+ application and a few rectangles to symbolise an obstacle. The "player" is a circle and moves with the arrow keys. The objective is to keep out of sight of the "enemies".

To detect if there is a line of sight what I wanted to do was draw a line from the player to the enemy and see if that line intersects any of the rectangular obstacles, but unfortunately I dont know how I would do this. Neither point can ever be inside the rectangle so I cant just do a simple check like that. So how would I check if the line intersects the obstacle?

And my other question is how to do circle-square intersection detection. If the player walks forwards I want to check if the circle player intersects any of the rectangular obstacles, and prevent them walking that way so that they dont go through it - simple collision detection.

Also it would help if I could do circle-circle intersections so that if I add a second enemy, they dont walk over each other, but this is an addition and not necessary.

So can anyone help me or point me to a tutorial on how I would detect these 2 or 3 kinds of intersections? I only need to know how to do them in 2D space.

Thanks
Tomas

2. For the tutorial, the best place to look is probably your high school math notebooks, if you still have them. Lines in 2D have the equation ax+by=c, so you'd have one equation for the line between player and enemy, one equation for the line that is the front of the box (or the side of the box). Solve the system of two equations in two unknowns.

Circles are easier; find the distance from the center of the circle to the line that is the front of the box; if it's less than the radius, then collision.