Mouse Click - check from inside Object
in
Programming Questions
•
1 year ago
What is the best way for an object to check if it has been clicked on?
Previously I have been using:
- //pseudo-code
- void mouseClicked(){
- loop through array of objects
- check if mouseX and mouseY inside the bounds each object in the array
- //do something
- }
I was wondering if there is a way to get each object to monitor whether it has been clicked and dispense with the array method entirely. Something like this:
- class Obj{
- void MouseClicked(){
- check if in bounds of this instance
- //do something
- }
- }
It appears that mousePressed don't work inside objects - I am guessing this is something to do with them being inside a class.
Am I thinking about this the right way? I haven't used event listeners yet. I'm not sure if they are what I want.
Here's some example code I have been working with:
- Circle[] circles = new Circle[11];
- void setup(){
- size(400,400);
- for(int i=0;i<circles.length;i++){
- circles[i] = new Circle(i*40,height/2,random(20,30), i);
- }
- }
- void draw(){
- for(int i=0;i<circles.length;i++){
- circles[i].display();
- }
- }
- class Circle{
- float x,y,w,h;
- int id;
- Circle(float x, float y, float w, int id){
- this.x = x;
- this.y = y;
- this.w = w;
- this.h = w;
- this.id = id;
- }
- void display(){
- ellipse(x,y,w,h);
- }
- void mouseClicked(){
- /*
- I want each circle to check if it has been clicked
- Can I do this from inside the circle class?
- Is there a way to do this without looping through the array in void draw?
- */
- println(id);
- }
- }
1