# Differences

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

 tutorials:point_in_rotated_object [2012/12/22 00:30]soule changed header etc tutorials:point_in_rotated_object [2013/03/05 10:19] (current) Both sides previous revision Previous revision 2012/12/22 01:10 soule added tip2012/12/22 00:50 soule added link2012/12/22 00:30 soule changed header etc2012/12/22 00:29 soule added title2012/12/22 00:29 soule created Next revision Previous revision 2012/12/22 01:10 soule added tip2012/12/22 00:50 soule added link2012/12/22 00:30 soule changed header etc2012/12/22 00:29 soule added title2012/12/22 00:29 soule created 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: + + -(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); + } + ​ + + 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