Search code examples
actionscript-3flashif-statementbooleanflashdevelop

Allow a button press by true or false variable AS3


I have been making an advent calendar in which when you press the button the door opens. I have created a variable to control which date you can open them on called 'AllowOpen' if it is the right date. I have also created a function to go to a frame when clicked.

var AllowOpen: Boolean = false;
if (Day == 1) {
    AllowOpen = true;
} else {
    AllowOpen = false;
}

button1.addEventListener(MouseEvent.MOUSE_DOWN, click);

function click(event:MouseEvent):void
{
    gotoAndStop(2)
}

I can't work out how I would tell the the program to only open the door if allow open is true. I have tried the 'if' statement but it doesn't seem to work. Thanks


Solution

  • OK, you could put the 'if' loop inside the function as already suggested thusly:

    function click(e:Event):void{
        if (AllowOpen) {
            gotoAndStop(2);
        }
    }
    

    BUT, spidey senses tingling. I would opt for adding an ENTER_FRAME listener so that as the day changes you automatically change boolean values for each day/door to open:

    var my_boolean_var_i:boolean = false;
    
    addEventListener(Event.ENTER_FRAME, checkDay);
    function checkDay(e:Event):void{
        if(Day == day_i){
            my_boolean_var_i = true;
        }
    }
    

    "i" would be another variable that you would declare to store an integer from 1 to 28 depending on the date and then a set of variables 'day + i'. Then you can have a listener/function for each door named sequentially with i to keep everything organized:

    door_i.addEventListener(Event.MOUSE_CLICK, click_i);
    function click_i(e:Event):void{
        if(my_boolean_var_i == true){
            gotoAndStop(2);
        }
    }
    

    This is the way I would go about settling the task. It's a lot of repetitive code so there is bound to be some more elegant way to do this from a more advanced user. Also, if you want to animate the door look up GreenSock TweenLite. VERY useful and friendly for graphics and whatnot.