Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Code Snippets / [AGK] Circle Line intersection

DBPro Master
Years of Service
User Offline
Joined: 16th Apr 2003
Location: Agartha
Posted: 11th Jan 2016 20:26
Want to move a circle from A to B but there's a big line in the way? Need to know where that circle makes contact and how to position the circle along that line? Then this snippet is for you!

This is what you might have heard as swept collision. From from A to B create a straight line. For instance, moving a ball around the screen, each frame it moves it has a start and end point. It might move in a circle, but each step is a straight line. If it moves too fast, it could appear to pass right through objects, thus you have to see if anything is in the way between A and B. For tiny bullets which move super fast (instantly), a simple intersection test between a line (AB) and an object is easy as the bullet has no real size. But what about a ball? The intersection point can place the ball in the middle of a wall, rather than putting its surface up against it.

The large commented section of code was my initial solution, which works just fine. However, someone pointed out I could just translate the wall (a line) by the radius of the ball. It's a much simpler solution. Translate the wall along it's normal towards A (the ball moving from A to B) then do the line-line intersection test. There, you now have the new position of your ball without going through the wall. If you want the point of contact, take the new ball position and add wall's normal to it with a magnitude equal to the radius of the ball. The result? Far shorter code and far less calculations.

+ Code Snippet

"I like offending people, because I think people who get offended should be offended." - Linus Torvalds

Login to post a reply

Server time is: 2017-07-22 03:53:35
Your offset time is: 2017-07-22 03:53:35