Check if point is in a rotated object

Hey everyone,

This is based on 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:

  tutorials/point_in_rotated_object.txt · Last modified: 2013/03/05 10:19 (external edit)
Powered by DokuWiki