@kadin
To make an object move towards the mouse in p5.js, you can use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Object { constructor(x, y) { this.x = x; this.y = y; } moveTowardsMouse() { let dx = mouseX - this.x; let dy = mouseY - this.y; let angle = atan2(dy, dx); this.x += cos(angle) * 5; this.y += sin(angle) * 5; } display() { fill(255); ellipse(this.x, this.y, 20, 20); } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
let obj; function setup() { createCanvas(400, 400); obj = new Object(width/2, height/2); } function draw() { background(0); obj.moveTowardsMouse(); obj.display(); } |
In this code, the object will continuously move towards the mouse cursor at a speed of 5 pixels per frame. You can adjust the speed by changing the value 5
in the moveTowardsMouse()
method.