xxxxxxxxxx
let eye1;
let eye2;
function setup() {
createCanvas(400, 400);
eye1 = new Eye(150, 150, 100);
eye2 = new Eye(250, 150, 100);
}
function draw() {
background(220);
// Calculate the angle to follow the cursor
let angle1 = atan2(mouseY - eye1.y, mouseX - eye1.x);
let angle2 = atan2(mouseY - eye2.y, mouseX - eye2.x);
// Update and display the eyes
eye1.update(angle1);
eye2.update(angle2);
eye1.display();
eye2.display();
}
class Eye {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.pupilSize = size * 0.5;
}
update(angle) {
let pupilX = this.x + cos(angle) * (this.size * 0.25);
let pupilY = this.y + sin(angle) * (this.size * 0.25);
let eyeRadius = this.size / 2;
let pupilRadius = this.pupilSize / 2;
let distance = dist(this.x, this.y, pupilX, pupilY);
if (distance < eyeRadius - pupilRadius) {
this.pupilX = pupilX;
this.pupilY = pupilY;
} else {
this.pupilX = this.x + cos(angle) * (eyeRadius - pupilRadius);
this.pupilY = this.y + sin(angle) * (eyeRadius - pupilRadius);
}
}
display() {
fill(255);
ellipse(this.x, this.y, this.size);
fill(0);
ellipse(this.pupilX, this.pupilY, this.pupilSize);
}
}