Calculating Position of Rectangle Corners
- January 14, 2010
- 4 replies
- 2092 views
Hello again everyone - I'm in the middle of attempting to write my own collision detection algorithm because the built in 'hitTestObject' function seems to be incredibly inaccurate (it's registering 'hits' when the objects are still a considerable distance from each other).
I need to be able to calculate the position of each of the 4 corners of a rectangle, based on its rotation. Obviously one of the corners will simply be the rectangle's x and y coordinates. I have made a little test program to make sure I am calculating the positions of the corners accurately - it works when the rectangle is rotated to 0, 90, 180 and 270 degrees, but produces strange results for any other angles...
I have attached the program at the bottom, but here is the code:
package
{
import flash.display.MovieClip;
import flash.geom.Point;
public class CornerFinder extends MovieClip
{
//vars
var myRect:MovieClip;
//constructor
public function CornerFinder():void
{
myRect = new MyRectangle();
myRect.x = stage.stageWidth/2;
myRect.y = stage.stageHeight/2;
myRect.rotationZ = 270;
addChild(myRect);
AddCornerMarkers();
}
private function AddCornerMarkers():void
{
//The rotation of the rectangle in radians
var rectRotation = myRect.rotationZ*(Math.PI/180);
var corners:Array = new Array();
corners[0] = new Point(myRect.x, myRect.y);
corners[1] = new Point( (myRect.x + myRect.width * Math.cos(-rectRotation)), (myRect.y + myRect.height*Math.sin((rectRotation) )) );
corners[2] = new Point( (myRect.x + myRect.width * Math.sin(-rectRotation)), (myRect.y + myRect.height*Math.cos((rectRotation) )) );
corners[3] = new Point(corners[2].x + (corners[1].x - corners[0].x) , corners[2].y + (corners[1].y - corners[0].y));
for(var i:uint = 0; i < corners.length; i++)
{
var marker:MovieClip = new CornerMarker();
marker.x = corners.x - marker.width/2;
marker.y = corners.y - marker.height/2;
trace("Adding marker at: " + marker.x + ", " + marker.y);
addChild(marker);
}
}
}
}
MyRectangle, as you may have guessed is a simple rectangular symbol that is in the library of my fla file. The CornerMarker is just a red circle symbol.
Can anyone see what the problem is? I thought if it worked for the 'main' angles (e.g. 0, 90, 180, etc) it would work for everything in between, but apparently not...
