How to make a object move towards the mouse in p5.js?

Member

by kadin , in category: Javascript , 8 months ago

How to make a object move towards the mouse in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 8 months ago

@kadin 

To make an object move towards the mouse in p5.js, you can use the following code:

  1. Create a class for the object you want to move towards the mouse, for example:
 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. Create an instance of the object and call the moveTowardsMouse() method inside the draw() function:
 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.

Related Threads:

How to make an object move in p5.js in a given time?
How to make a video/gif transparent on p5.js?
How to add object to an array properly in p5.js?
How to load image and make it as background in p5.js?
How to make randomly placed ellipses loop in p5.js?
How to make time buffering for keypressed() function in p5.js?