I have two classes Circle and Square which derive from an abstract base class Shape.

A Shape*array stores pointers to the Circle and Square objects (which include their random position in a 2D grid).

The objective is to determine which shapes in the array overlap and the objects themselves should contain the methods to calculate this. For example, the Square class would have methods: bool overlapsWithSquare(Shape s) and bool overlapsWithCircle(Shape s).

My idea is to construct two for loops which compare each and every shape in the array, however, how would my program know which method to call upon as we don't know what sub-type each Shape object is?

If the actual type was known, I could have two virtual methods in each object, bool overlaps(...) with different parameters Square s and Circle c.

I had solved a similar problem by simplifying my geometry. In my case there was only one such function: bool overlaps(Shape)

A shape was just a list of floats, and the collision logic switched internally based on that list using the following logic:

  • A shape with only 3 values was assumed to be a circle [x, y, radius]
  • A shape with only 4 values was assumed to be a line [x1, y1, x2, y2]
  • A shape with any even number of values > 4 is a polygon [x1, y1, ... xn, yn]
  • Any shape with an odd number of values >= 5 is not a valid shape

Also worth looking into is the Separating Axis Theorem. This is what I was using in my physics engine. It works really well if you're only using convex polygons.

This article did wonders for me understanding this in case you haven't chosen a method for actually implementing your overlaps function yet: http://www.metanetsoftware.com/technique/tutorialA.html

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.