Referencing a object that is on the stage inside a class?

最后都变了- 提交于 2019-12-25 04:15:07

问题


So I had the issue with ENTER FRAME so I moved it to a separate class and this is what the class looks like

 package  {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.accessibility.Accessibility;
    import flash.display.DisplayObject;
    import flash.display.Stage;


    public class enemy extends MovieClip {

        public function enemy() {
            // constructor code

            this.addEventListener(Event.ENTER_FRAME, moveEnemy);

        }
    public function moveEnemy(e:Event):void{

        this.x += 5;
        if(stage.player.scaleX == 1){
            this.scaleX = 1;
            }else {
                this.scaleX = -1;
                }

        }
    }

}

Now Im trying to adjust the enemies scalex according to the players but I get a error when referencing the player inside the class can anyone help me solve this?


回答1:


The trick with using Event.ENTER_FRAME listener is that event.currentTarget will hold the link to the object that's processing the event, event.target will hold the link to the object that's received it first, so you can attach the listener not to the stage, but to the MovieClip of your choice, including having more than a single listener across your game. Say, you give your Enemy class a listener that's making it query stage's list of player's bullets and check collisiong against this, a player can do this too. Or, you use a single listener and do ALL the work inside it, using local arrays to store lists of enemies, bullets, player(s) and other objects.

In terms of passing parameter to enter frame listener - your event is automatically dispatched, so you shouldn't bother with this, and it does not accept more than one parameter.

Regarding your code, you should add enemy movement code in testPlayerCollisions() listener below querying for player collision. For this, you already have an enemy you're about to move, so you just have to call its move() function or whatever you have for it.




回答2:


It looks like your enemy class doesn't have access to the stage; yet you're trying to reference stage.player. You can access the stage from your main class but not from other classes unless you pass it through the constructor.

Try passing the stage to the enemy class and create a class variable to store it. Ie:

private var stageInst:Stage;

public function enemy(s:Stage){
    stageInst = s;   
}

Then in moveEnemy use stageInst.player to access the player's clip.

When you create enemy's you'll have to pass in an instance of the stage from Main.

ie: var e:enemy = new enemy(stage);



来源:https://stackoverflow.com/questions/15594810/referencing-a-object-that-is-on-the-stage-inside-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!