xxxxxxxxxx
49
/*
----- Coding Tutorial by Patt Vira -----
Name: Collision Detection (Circle to Rect)
Video Tutorial: https://youtu.be/gUTeWOfwECc?si=c6VZPQRFRp4MMSW4
Connect with Patt: @pattvira
https://www.pattvira.com/
----------------------------------------
*/
let x; let y; let w = 100; let h = 50;
let cr = 15;
function setup() {
createCanvas(400, 400);
x = width/2;
y = height/2;
}
function draw() {
background(220);
let closeX = mouseX;
let closeY = mouseY;
if (mouseX > x + w) {
closeX = x + w;
} else if(mouseX < x){
closeX = x;
}
if (mouseY > y + h){
closeY = y + h;
} else if (mouseY < y) {
closeY = y;
}
let distX = closeX - mouseX;
let distY = closeY - mouseY;
let distance = sqrt((distX * distX) + (distY * distY));
if (distance <= cr) {
fill(255, 255, 0);
} else {
fill(255);
}
rect(x, y, w, h);
fill(255, 0, 0);
ellipse(mouseX, mouseY, cr*2, cr*2);
}