Adding a object randomly on the screen in as3

2019-09-02 22:39发布

问题:

OK, so i am having trouble with adding a box randomly on the screen. I have done this before and it seems like it should have a relatively easy solution. But alas, i have not been able to figure this out. This is the info:

I have a box mc with exporting as Box. I have a Box Actionscript file with this code in it:

package {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
public class Box extends MovieClip {

    public function Box() {
        createBox();

    }

    private function createBox():void {

        var _box:Box = new Box();
        _box.x = Math.random()*stage.stageWidth ;
        _box.y = Math.random()*stage.stageHeight;
        stage.addChild(_box);

    }
}
}

Nothing happens at all but there is no errors. Also i would like to keep everything in the classes.

回答1:

There is a thing in your code because of that code is not working:

1) when you are using class as a Document class then the class name should be unique i.e name of Document class is not associated with any library symbols.

package   
{
    import flash.display.MovieClip;  
    import flash.events.Event;  
    import flash.events.MouseEvent;  

    public class Main extends MovieClip 
    {
        private var _box:Box = new Box();

        public function Main() 
        {
            createBox();
        }

        private function createBox():void 
        {
            trace(Math.random()*stage.stageWidth)
            _box.x = Math.random()*stage.stageWidth ;
            _box.y = Math.random()*stage.stageHeight;
            stage.addChild(_box);   
        }
    }
}