No specific goal other than that I want to figure out where the mouse would be if it were expressed in model coordinates. It would be useful functionality in a handful of scenarios.
I figured out how to do it for JAVA2D
and P2D
, but things get a little weird with P3D
.
@Override
public void settings() {
size(800, 800);
}
@Override
public void draw() {
background(0);
translate(50, 50);
rotate(PI / 8f);
PVector modelMouse = ModelMouse(this);
circle(mouseX, mouseY, 10);
circle(modelMouse.x, modelMouse.y, 10);
}
public static PVector ModelMouse(PApplet app) {
PMatrix currentMatrix = app.getMatrix();
currentMatrix.invert();
return currentMatrix.mult(new PVector(app.mouseX, app.mouseY, 0), null);
}
Here, the first circle is drawn where you’d expect it to be, given the transformations. The second circle is drawn at the mouse’s location.
When you switch to size(800, 800, P3D)
, the first circle is the same. But the second circle seems to be in the middle of the screen. I’ve figured out that you can compensate for that by subtracting half a screen from the mouse before doing the reverse transformation.
public static PVector ModelMouse(PApplet app) {
PMatrix currentMatrix = app.getMatrix();
currentMatrix.invert();
PVector mouse = new PVector(app.mouseX, app.mouseY, 0);
if(app.g.is3D()) {
mouse.x -= app.width / 2f;
mouse.y -= app.height / 2f;
}
return currentMatrix.mult(mouse, null);
}
Then I can also draw the sphere at the mouse like this. The method is generalized so I can add it to my custom PAppletUtility class
push();
translate(modelMouse.x, modelMouse.y);
sphere(100);
pop();
So I guess I got it. Took a hot annoying sec to figure out. I don’t know if this is the best way though or why I need to do that weird compensation for P3D
.