I’ve been working on a code library recently. Since I don’t have much to blog about, I figure I’d share a piece from the library every day (and maybe more often). Today, you get my handy DisplayObject rotator class.
package libTF { import flash.display.DisplayObject; import flash.geom.Point; public class Rotator { public static function rotateAboutInternalPoint(obj:DisplayObject, pt:Point, amt:Number):void { var dist:Number = Math.sqrt(pt.x * pt.x + pt.y * pt.y); var ang:Number = Math.atan2(pt.y, pt.x); pt.x = Math.cos(ang + obj.rotation * Math.PI / 180) * dist; pt.y = Math.sin(ang + obj.rotation * Math.PI / 180) * dist; rotateAboutRelativePoint(obj, pt, amt); } public static function rotateAboutRelativePoint(obj:DisplayObject, pt:Point, amt:Number):void { obj.rotation += amt; var dist:Number = Math.sqrt(pt.x * pt.x + pt.y * pt.y) var ang:Number = Math.atan2( pt.y, pt.x) * 180 / Math.PI + amt; obj.x += -Math.cos(ang * Math.PI / 180) * dist + pt.x; obj.y += -Math.sin(ang * Math.PI / 180) * dist + pt.y; } public static function rotateAboutCoordinatePoint(obj:DisplayObject, pt:Point, amt:Number):void { pt.x -= obj.x; pt.y -= obj.y; rotateAboutRelativePoint(obj, pt, amt); } public static function rotateTowardsAngle(obj:DisplayObject, ang:Number, rot:Number, limit:Boolean = true):void { var ang1:Number = obj.rotation % 360; if (ang1 < 0) {ang1 += 360; } ang %= 360; if (ang < 0) { ang += 360; } var da:Number = ang - ang1; if (Math.abs(da) < rot) { obj.rotation = ang; } else if (da > 180 || (da < 0 && da > -180)) { obj.rotation -= rot; } else if ((da > 0 && da <= 180) || da < -180) { obj.rotation += rot; } } public static function rotateTowardsInternalPoint(obj:DisplayObject, pt:Point, rot:Number, limit:Boolean = true):void { var dist:Number = Math.sqrt(pt.x * pt.x + pt.y * pt.y); var ang:Number = Math.atan2(pt.y, pt.x); pt.x = Math.cos(ang + obj.rotation * Math.PI / 180) * dist; pt.y = Math.sin(ang + obj.rotation * Math.PI / 180) * dist; rotateTowardsRelativePoint(obj, pt, rot, limit); } public static function rotateTowardsRelativePoint(obj:DisplayObject, pt:Point, rot:Number, limit:Boolean = true):void { rotateTowardsAngle(obj, Math.atan2(pt.y, pt.x), rot, limit); } public static function rotateTowardsCoordinatePoint(obj:DisplayObject, pt:Point, rot:Number, limit:Boolean = true):void { rotateTowardsAngle(obj, Math.atan2(pt.y - obj.y, pt.x - obj.x), rot, limit); } public static function rotateTowardsMouse(obj:DisplayObject, rot:Number, limit:Boolean = true):void { if (obj.parent) { rotateTowardsAngle(obj, Math.atan2(obj.parent.mouseY - obj.y, obj.parent.mouseX - obj.x) * 180 / Math.PI, rot, limit); } } } }