Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorials:point_in_rotated_object [2012/12/22 00:50] – added link souletutorials:point_in_rotated_object [2013/03/05 10:19] (current) – external edit 127.0.0.1
Line 1: Line 1:
 +====== Check if point is in a rotated object ======
  
 +Hey everyone,
 +
 +This is based on [[http://developer.coronalabs.com/code/checking-if-point-inside-rotated-rectangle|this Corona snippet]]. (I just converted it to Obj-C :P)
 +
 +You'd probably use this for collision detection and run this in the enter frame:
 +<code objc>
 +-(bool) isPoint:(SPPoint *)point inRotatedObject:(SPDisplayObject *)obj {
 +    double c = cos(-obj.rotation * (PI/180));
 +    double s = sin(-obj.rotation * (PI/180));
 +    float rotatedX = obj.x + c * (point.x - obj.x) - s * (point.y - obj.y);
 +    float rotatedY = obj.y + s * (point.x - obj.x) + c * (point.y - obj.y);
 +    
 +    float leftX = obj.x - obj.width/2;
 +    float rightX = obj.x + obj.width /2;
 +    float topY = obj.y  - obj.height /2;
 +    float bottomY = obj.y + obj.height /2;
 +    
 +    return (leftX <= rotatedX && rotatedX <= rightX && topY <= rotatedY && rotatedY <= bottomY);
 +}
 +</code>
 +
 +So, if you have a rotated object, it will tell you if a point is in it. Normally, you could just get the object's bounds, but when an object rotates its bounds grow to accomodate all sizes so you cannot do that. 
 +
 +This basically "un-rotates" the bounds and checks if the point would be in there.
 +
 +Happy coding, and perhaps I should add an example? :)
 +
 +__If you are having performance issues__, try changing the floats to integers (tip from Roger Clark)
 +
 +(forum question here: http://forum.sparrow-framework.org/topic/collision-detection-for-rotating-object)
 
 
Powered by DokuWiki