Monday, December 19, 2016

objective c - In Cocos2D, how do I check for collisions against an arbitrary user-drawn shape?


I want to detect a collision between a sprite and a user-generated shape of some sort.


For example. There are 3 objects on the screen. The user takes their finger and draws an abnormal shape around 2 of the objects. I need to detect those 2 objects.


user shape in purple, game objects in green and red



How do I approach this efficiently using Cocos2D?



Answer



There's a very easy solution for that particular example.


I'm assuming your arbitrary shape is just a series of points.


Draw a ray from each of your objects in any direction. If the number of times it intersects a line segment on your shape is even (including zero), you are outside of the shape.


If the number of times you intersect is odd, you are inside the object.


Ray/line segment collision is a pretty easy algorithm to find/implement.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...