Reputation: 221
Im trying to move elements from one place to another place by randomly telling where to go from an array. But it is not acting as I was hoping it would.
the code is this
public class Main extends MovieClip
{
private var positions:Array = [ 0, 100, 200 ];//different X positions
public function Main()
{
for( var i:int = 0; i < 3; i++)
{
var box:Sprite = new Sprite();
box.graphics.beginFill( Math.random()*0xffffff );
box.graphics.drawRect( 100* i, 0, 80, 80);
box.graphics.endFill();
this.addChild( box );
box.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
private function onBoxClick( ev:MouseEvent ):void
{
var currentObj:Sprite = ev.currentTarget as Sprite;
var randomNumber:int = Math.random() * positions.length;
currentObj.x = positions[ randomNumber ];
currentObj.y = 200;
positions.splice( randomNumber, 1 );
}
}
as you can see i remove the X position that was given so that 2 elements can have the same position on the stage.But what the code does is it takes the current X position of the element and it adds to that the new X position. So if i click on element 1 and get position 2, click on element 2 and get position 1 and click on element 3 and get position 0 it would be this:
element1.x (0) + 200 = 200;
element2.x (100) + 100 = 200;
element3.x (200) + 0 = 200;
and they will be all in the same spot ( 1 over other).
and what I want is to do This:
element1.x (no matter where it is ) + 200 = 200;
element2.x (no matter where it is ) + 100 = 100;
element3.x (no matter where it is ) + 0 = 0;
I tried doing this
currentObj.x = 0 + positions[ randomNumber ];
or
currentObj.x = stage.x + positions[ randomNumber ];
but then it (the current element) still counts its current location as the '0' and adds to it.
Am i missing something?
Upvotes: 0
Views: 125
Reputation: 56442
Change this line :
box.graphics.drawRect( 100* i, 0, 80, 80);
By this :
box.graphics.drawRect(0, 0, 80, 80);
box.x = 100 * i;
It should work better then.
Your problem is you're drawing from a displaced point in the "box". So, when you're moving it's x, the displacement is summing up.
Drawing it at a 0 point will allow you to remove that offset.
Upvotes: 1