Question

am having problem with using mouse click event inside a class, i am an absolute beginner to Action Script.

what i want is that if i click the btn_MClick button it should run the script, but everytime i click it i get error message that btn_MClick is undefined.

btn_MClick is on stage and with the instance name if btn_MClick

public class gunShip1 extends MovieClip
{
    var moveCount = 0;

    public function gunShip1()
    {
        stage.addEventListener(KeyboardEvent.KEY_DOWN, moveGunShip1);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, ShootGunShip1)
                    btn_MClick.addEventListener(MouseEvent.MOUSE_DOWN.KEY_DOWN,   ShootGunShip1);;

    }


function ShootGunShip1(evt: MouseEvent)
{


            var s_Bullet:survBullet = new survBullet();
            var stagePos:Point = this.localToGlobal (new    Point(this.width / 2-10, this.height));;
            s_Bullet.x = stagePos.x;
            s_Bullet.y = stagePos.y;

            parent.addChild(s_Bullet);
            //play sound
            var gun_sound:ricochetshot = new ricochetshot();
            gun_sound.play();
        }
}

Please, i have absolutely no idea what to do, and somehow it feels like the whole process is wrong.

Was it helpful?

Solution

Your class gunShip1 does not have the property btn_MClick, the root, or document class does.

Basically what's happening is that you've placed your button on the stage, which makes it an instance that belongs to the root container. At the moment, you're trying to refer to the button as a property of gunShip1.

What you should really do here is have the button click managed separately to gunShip1, and have that separate code invoke methods of gunShip1. For example, you could have this in your document class:

public class Game extends MovieClip
{

    private var _ship:gunShip1;


    public function Game()
    {
        _ship = new gunShip1();

        // The Document Class will have reference to objects on the stage.
        btn_MClick.addEventListener(MouseEvent.CLICK, _click);
    }


    private function _click(e:MouseEvent):void
    {
        _ship.shoot();
    }

}

And then your updated shoot method in gunShip1:

public function shoot():void
{
    var s_Bullet:survBullet = new survBullet();
    var stagePos:Point = this.localToGlobal (new Point(this.width / 2 - 10, this.height));
    s_Bullet.x = stagePos.x;
    s_Bullet.y = stagePos.y;
    parent.addChild(s_Bullet);

    var gun_sound:ricochetshot = new ricochetshot();
    gun_sound.play();
}

The idea is that the gunShip1 should not be responsible for dealing with user input (mouse, keyboard, etc). Instead, that should be a separate class which informs gunShip1 that it should do something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top