We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hey, so I'm still working on my space invaders game & got tons of buttons. Each button has a long line of code to check if the mouse is on it & every time I make I new button. I gotta change the long line of code here and there. I was wondering if there a way to shorten the line. I got a button class & an array holding the buttons.
here the long line of code;
if (mouseButton == LEFT && mouseX < button[3].x+button[3].w/2 && mouseX > button[3].x-button[3].w/2 && mouseY < button[3].y+button[3].h/2 && mouseY > button[3].y-button[3].h/2){ /// this the line I'm wondering if there a way to shorten
if (room == 0){
exit();
}
}
if (mouseButton == LEFT && mouseX < button[4].x+button[4].w/2 && mouseX > button[4].x-button[4].w/2 && mouseY < button[4].y+button[4].h/2 && mouseY > button[4].y-button[4].h/2){ /// this the line I'm wondering if there a way to shorten
if (room == 2 || room == 3){
room = 0;
}
}
if (mouseButton == LEFT && mouseX < button[5].x+button[5].w/2 && mouseX > button[5].x-button[5].w/2 && mouseY < button[5].y+button[5].h/2 && mouseY > button[5].y-button[5].h/2){/// this the line I'm wondering if there a way to shorten
if (room == 4){
doubleShot = true;
}
}
Answers
Yes, but it's more trouble than it's worth unless you have more than about 10 buttons. You could have a Button object that you extend for each different action - or a switch statement that does different actions based on a Button's id. And the class would handle all the mouse position checks for you.
(Not a finished example!)
would all that happen in button or do I still need to check in mouseButton too?
in mousPressed() (outside any class!) you for-loop
i
over all buttons in the current (!!!) room and check withif(button[i].over()) { }
if it's clickedty
Actually I would just call click() on all my buttons, as they can check that the mouse is over them. Up to you.
ok, is button still array in main? for this?
yes
if (mouseButton == LEFT) {
is it still an array in the main script? ty for your time and answering my questions.
Yes
Button[] button = new Button [10];
or how many you need
ty, i'm trying to fill in everything and understand it at same time. It looks like in this code the room is array I had mine classes. I'm confused of how to place my class rooms in the array.