Here i have an actionscript3 code in which i am creating an array of objects. Basically in the array are multiple instances of the same object. I want to make an event listener which calls a function f0 which rotates the object 90 degrees. My problem is i can't find a way to asign unique identifiers to each object in array, so when i click an object i want it to rotate, but only the first element of the array rotates. I also want to center my rotation so that the object doesn't rotate in (0,0).
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.ColorTransform;
public class Main extends Sprite
{
var array = new Array();
var i:int;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
for (var i:int = 0; i < 10; i++)
{
var asd:Sprite = new Sprite();
asd.graphics.beginFill(0x0000ff);
asd.graphics.drawRect(0, 0, 60, 60);
array.push(asd);
addChild(array[i]);
array[i].x = 60 * i ;
array[i].y = 60 * i ;
array[i].addEventListener(MouseEvent.CLICK, f0);
if (i % 2 == 0) {
asd.graphics.lineTo(asd.x + 60, asd.y + 60);
}
removeEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function f0(e:Event):void
{
array[i].rotation += 90;
}
}
}
The event.target points to the object that the event handler was added to, you can use that to rotate the correct sprite.
private function init(e:Event = null):void
{
for (var i:int = 0; i < 10; i++)
{
createObject(i);
}
}
private function createObject(index:int):void
{
var asd:Sprite = new Sprite();
asd.graphics.beginFill(0x0000ff);
asd.graphics.drawRect(0, 0, 60, 60);
array.push(asd);
addChild(asd);
array[index].x = 60 * index ;
array[index].y = 60 * index ;
array[index].addEventListener(MouseEvent.CLICK, f0);
if (index % 2 == 0) {
asd.graphics.lineTo(asd.x + 60, asd.y + 60);
}
}
private function f0(e:Event):void
{
e.target.rotation += 90;
}
To rotate a object around it's center you can do :
private function rotateAroundCenter (ob:DisplayObject, angleDegrees:Number):void
{
var matrix:Matrix = ob.transform.matrix;
var rect:Rectangle = ob.getBounds(this.parent);
matrix.translate(- (rect.left + (rect.width/2)), - (rect.top + (rect.height/2)));
matrix.rotate((angleDegrees/180)*Math.PI);
matrix.translate(rect.left + (rect.width / 2), rect.top + (rect.height / 2));
ob.transform.matrix = matrix;
}
This transforms the objects center to (0,0) rotates it and then translates the object back to it's original position. It will only work if the objects has a parent and it's width height is non zero.