MandyLB
MandyLB

Reputation: 317

How to determine the distance in pixels between a circle and various obstacles

So I have a circle created in pygame as my main character, and I'm looking to find the shortest distance between its sides and the various surrounding obstacles. You can see what I mean in the picture. I have a left quadrant and a right quadrant, and I want to see what exists in these quadrants. Whatever is the closest obstacle pixel wise to the circle, that pixel count becomes the left and right values (ie. if in the right quadrant the closest obstacle was 40 pixels away, right = 40). I also have a front value, that will be scanning for things directly in front of the circle.

I've seen things for looking for collision with a circle (creating a circular field around the object as a whole) and I've also seen stuff that uses Pythagorean theorem to look for distances, but I'm not sure how to tackle it in a more "spotlight" scope, if that makes sense.

Any suggestions on how to go about this would be much appreciated! The overall goal is for the circle to move automatically around these obstacles by avoiding them, hence why I want it to scan in various areas to determine how to move about the space.

The entire space is enclosed with a wall, and all the obstacles are randomly placed squares within the wall.

circle moving

Upvotes: 0

Views: 149

Answers (1)

user1196549
user1196549

Reputation:

The distance to a circle is the same as the distance to the center minus the radius.

Now, the distance from a rectangle to a point is found by considering the nine regions defined by the supporting lines of the sides.

Depending on the region, the shortest distance is axis-aligned (from a side to the point) or oblique (from a corner to the point) and the formulas are easy.

enter image description here

The discussion is even simpler for a rectangular hole or inner angle.

Upvotes: 1

Related Questions