Skip to main content
Participant
September 12, 2014
Answered

How to simplify this function ?

  • September 12, 2014
  • 3 replies
  • 254 views

Hello, I am trying to add fish of different colors on the canvas by triggering a function on a button click, each color has its own movieclip (in this case, fishred and fishblue)).

The thing is that the function are all the same but only the var for color changes, and I have to make multiple colors.

Is there a way to change it into a single function that will choose which movieclip will be added when clicking on a specific button ?

var red:fishred = new fishred();

var blue:fishblue = new fishblue();

function addRed(e:Event) {

    if (red.stage) {

        red.parent.removeChild(red);

    } else {

        red.x = Math.random() * 550;

        red.y = Math.random() * 400;

        red.dx = Math.round(Math.random() * 550);

        red.dy = Math.round(Math.random() * 400);

        addChild(red);

    }

function addBlue(e:Event) {

    if (blue.stage) {

        blue.parent.removeChild(red);

    } else {

        blue.x = Math.random() * 550;

        blue.y = Math.random() * 400;

        blue.dx = Math.round(Math.random() * 550);

        blue.dy = Math.round(Math.random() * 400);

        addChild(blue);

    }

}

This topic is closed to new replies. Start a new post to keep the conversation going.
Correct answer Ned Murphy

If you assign a property to each button that is the same as the name of its corresponding fish color then you could just use the e.currentTarget property to identify which button was clicked and use that button's property to target the fish...

function addFish(e:Event) {

    var fish:String = e.currentTarget.color_name;

    if (this[fish].stage) {

       this[fish].parent.removeChild(red);

    } else {

        this[fish].x = Math.random() * 550;

        this[fish].y = Math.random() * 400;

        this[fish].dx = Math.round(Math.random() * 550);

        this[fish].dy = Math.round(Math.random() * 400);

        addChild(this[fish]);

    }

}

3 replies

Ned Murphy
Ned MurphyCorrect answer
Legend
September 12, 2014

If you assign a property to each button that is the same as the name of its corresponding fish color then you could just use the e.currentTarget property to identify which button was clicked and use that button's property to target the fish...

function addFish(e:Event) {

    var fish:String = e.currentTarget.color_name;

    if (this[fish].stage) {

       this[fish].parent.removeChild(red);

    } else {

        this[fish].x = Math.random() * 550;

        this[fish].y = Math.random() * 400;

        this[fish].dx = Math.round(Math.random() * 550);

        this[fish].dy = Math.round(Math.random() * 400);

        addChild(this[fish]);

    }

}

Participant
September 13, 2014

Took me time to understand what to change but it works !! Thank you !

Ned Murphy
Legend
September 13, 2014

You're welcome