Copy link to clipboard
Copied
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);
}
}
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[f
...Copy link to clipboard
Copied
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]);
}
}
Copy link to clipboard
Copied
Took me time to understand what to change but it works !! Thank you !
Copy link to clipboard
Copied
You're welcome
Find more inspiration, events, and resources on the new Adobe Community
Explore Now