简体   繁体   中英

JavaScript Canvas Complex Shape Collision

I am trying to make a very simple game with the HTML canvas and JavaScript. I have found many tutorials and questions about detecting collisions of basic shapes on a canvas (such as rectangles and circles). But I am wondering is it possible to detect if a complex shape (a shape that is made up of many basic shapes) is colliding with another shape, or even if two complex shapes are colliding. If so, how could this be done? Thanks in advance!

A general algorithm will not provide a better solution than one based specifically on the knowledge of each shape type.

Generally, for complex (ie compound) shapes, you would generally try as step #1 and "exit early" test. For optimization reasons, you generally try eliminate false-positives as early in the process as possible.

As simple step #1 is to test for collisions on the "bounding boxes" of each compound shape. If the bounding boxes are NOT overlapping then you can quit early and assume no collision because the compound shapes could not be colliding (see https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169 )

If the bounding-box test cannot eliminate early, you will need to test each sub-shape in turn with algorithms most suitable to the shape (circle-circle, circle-rect etc.) leaving the most "expensive" tests to last - like polygon-polygon.

You might want to also look at this question How do I determine if two convex polygons intersect?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM