Working with mouseDragged() and other mouse events inside a class

I usually work with the philosophy of “code now, fix later”. However, in my recent work, I’ve been trying to plan out my code ahead of time. So my question right now is, what’s the best way for working with mouseDragged() inside a class?

In the past, I just put a little bit of the detection in mousePressed(), a little in mouseDragged(), and the rest bouncing around in global variables. But I figure there’s got to be a better way. Here’s some of my spaghetti code if you want to take a look.

I have considered using p5.Elements to access their mouseOver() and mousePressed() functions, but unlike Processing, they don’t have a mouseDragged() method.

The Question:

  • Can I detect mouse-stuff within a class definition?

Anyways, my eventual hope is to have a class that implements the kind of drag-and-drop interface in the sketch above all in one neat class definition.

Callback mouseDragged() is merely a fancy mouseMoved() which also checks for mouseIsPressed. :computer_mouse:

In this online p5js sketch below: :blush:

Function rotateCube() is chosen as the mouseMoved() callback for the sketch’s <canvas>: :black_square_button:
createCanvas(400, 400).mouseMoved(rotateCube);

And inside rotateCube(), mouseIsPressed is checked in order to emulate mouseDragged(): :heavy_check_mark:

function rotateCube() {
  if (mouseIsPressed) {
    rotateY3D(mouseX - pmouseX, nodes);
    rotateX3D(mouseY - pmouseY, nodes);

  ({ mouseX: pmouseX, mouseY: pmouseY } = window);
1 Like

Thanks for the reply!

({ mouseX: pmouseX, mouseY: pmouseY } = window);

Also, what kind of assignment is this?

({ mouseX: pmouseX, mouseY: pmouseY } = window);
is equivalent to:
pmouseX = window.mouseX, pmouseY = window.mouseY;
and b/c prefixing w/ window is optional, just:
pmouseX = mouseX, pmouseY = mouseY;

That technique is called “Object Destructuring Assignment”, btW: :man_technologist:

This is just a temporary workaround though. :face_with_head_bandage:
p5js fails to update pmouseX & pmouseY for p5.Element mouse callbacks! :face_with_thermometer:
I believe they might be fixing it now, not sure. :roll_eyes:

1 Like

I was looking at the p5.Element reference, and they mention that graphics buffers are considered elements. How does that work? I messed around a little with a PGraphic below:

  class MyClass
		this.g = createGraphics(20,20);
		this.g.mouseOver( function(){ println("BLEGH"); });
		image(this.g, 100, 100);

While it does have a position, it gets drawn separately. How do I access the mouse-events if it’s not an actual object on the screen?

Edit: Literally a minute later I got it working. Though now the purpose of defining dimensions with both createGraphics() and g.size() confuses me :thinking:

Also, pixelDensity() is janky.