Created
December 20, 2019 00:11
-
-
Save devinhalladay/bb29e4ec602e55760100286f2614918b to your computer and use it in GitHub Desktop.
handle clicks on objects in p5. handles circles and rectangles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Square(x, y, w, h) { | |
this.x = x; | |
this.y = y; | |
this.w = w; | |
this.h = h; | |
// this.[thing] syntax is used to scope a variable locally to the class | |
// again using this. to scope this function locally so you can call it with [squareInstance].display(); | |
this.display = function() { | |
stroke(255); | |
fill(255); | |
rect(this.x, this.y, this.w, this.h); | |
} | |
// here's our click handler | |
this.clicked = function() { | |
// var d = dist(mouseX, mouseY, this.x, this.y); | |
// for circles it's d < this.radius/2 | |
// for squares this is what I came up with but there might be a more efficient way to detect if you're inside the bounds. You can prob utilize the `d` var above but i couldn't make it work | |
if(mouseX >= this.x && mouseX <= this.x+width && | |
mouseY >= this.y && mouseY <= this.y+height){ | |
// do something on click | |
console.log('clicked' + this); | |
} | |
}; | |
}; | |
var squares = []; | |
function setup() { | |
createCanvas(400, 400); | |
background(0); | |
// Add random squares; I think you need to instantiate the class in setup or maybe in another function but NOT in draw, since draw loops and will crash ur sketch | |
for(var i = 0; i < 10; i++){ | |
var x = random(width); | |
var y = random(height); | |
// this creates a new instance of the Square class and pushes it into the squares array | |
squares.push(new Square(x,y, 60, 24)); | |
} | |
} | |
function mousePressed() { | |
for(var i = 0; i < squares.length; i++){ | |
// loop through the squares array and call the `clicked` method of the Square object | |
squares[i].clicked(); | |
} | |
} | |
function draw() { | |
for(var i = 0; i < squares.length; i++){ | |
// Actually draw the squares we pushed during setup | |
squares[i].display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment