Objects with Timer in AS3
I have this class named MovingObject which extends the MovieClip class. This class will be instantianted for several times. Inside this class is a Timer that handles the speed of the objects moving. There is another class called TheStage and this is where I will instantiate MovingObject (s).
public class开发者_如何学Go MovingObject extends MovieClip{
public var tmr:Timer = new Timer(1);
public function MovingObject(){
tmr.addEventListener(TimerEvent.TIMER, Move);
}
public function StartMove():void{
this.tmr.start();
}
public function ChangeSpeed(delay:Number):void{
this.tmr.delay = delay;
}
public function Move(evt:TimerEvent):void{
// some codes to make this.x and this.y change
}
}
public class TheStage extends MovieClip{
public var objectArray:Array = [];
public function TheStage(){
var x:int =0;
var mcMoveObject;
while (x!=10){
mcMoveObject = new MovingObject();
mcMoveObject.x += 10;//offset between the objects
mcMoveObject.y += 10;//offset between the objects
this.addChild(mcMoveObject);
objectArray.push(mcMoveObject);
mcMoveObject.tmr.start();
x++;
}
}
public function ChangeSpeed(delay:Number):void{//some function to change speed
for(var chilCnt:int =0;chilCnt<objectArray.length; chilCnt++){
objectArray[chilCnt].timer.delay = delay;
}
}
}
Assuming that the code is working fine (I haven't debugged it), this makes the particles to move all at once. However after several seconds of running it, the particles seem not to be moving in synchronization with each other (because their distances between seem to get nearer). I need some help to make the objects move with their distances each other evened out.
With the code as is, you will only see one particle on stage, the following code doesn't offset your objects!
mcMoveObject = new MovingObject(); mcMoveObject.x += 10;//offset between the objects mcMoveObject.y += 10; //since you're instantiating a new MovingObject +=10 doesn't do what you expect // it simply sets a value of 10 for x & y.
You would need to do this
var objX:int; var objY:int; while( x!=10 ) { objX +=10; objY +=10; mcMoveObject = new MovingObject(); mcMoveObject.x = objX; mcMoveObject.y = objY; //etc....
Then, why do you call this?
mcMoveObject.tmr.start();
when you could do this
mcMoveObject.StartMove();
Have you actually tried this code? I don't see why your MovingObjects would get out of sync, right now they should all move together.
精彩评论