2D screen and 'world' position coordinates

I’m making a UI based on zooming and dragging (2d) . Basically I’m trying:

function draw() {
    background(185, 175, 185);

    translate(width/2, height/2);
    translate(dragPos.x , dragPos.y);
    for (const b of bodies) {

and I’ve tried a silly

function screenToWorld(x, y) {
    let worldX = (x - dragPos.x - width/2) / zoom;
    let worldY = (y - dragPos.y  - height/2) / zoom;
    return createVector(worldX, worldY);

function worldToScreen(x, y) {
    let screenX = (x * zoom) + dragPos.x + width/2;
    let screenY = (y * zoom) + dragPos.y + height/2;
    return createVector(screenX, screenY);

Well, did not work… almost though :smiley:
How can i keep track of the translation from transformed coordinates to mouse (screen)?
So mouse can interact with stuff based on being over or not …

The code is in progress and have a lot more going on, so I tried to isolate here the stuff about this point.
There is a running playground with the malfunctioning code here

How can I do it?

1 Like

Take a look at the math here: Using the mouse position to zoom in on a map - #10 by scudly

and here’s one that supports rotation as well as pan and zoom: https://www.reddit.com/r/processing/comments/aecgdp/using_a_mousebased_ui_to_explore_truchet_tiles/

1 Like

Thanks @scudly, gonna dive into this, but at first look * the first code has a very buggy zoom implemented. The second one works great. But, as I said I will need to dive in it to understand it.
thanks for the links.

I’ll post my finds later
: )

* in processing IDE was really weird, but translated to p5 the zooming is working fine. I still on that :slight_smile: here the translation

I find it!
Well @scudly both yours codes are amazing and I learned a lot from them. Thanks.
I end up finding where was my problem while trying to adapt your approach to my scenario.
My screenToWorld() function was applying things in wrong order…
instead of

let worldX = (x - dragPos.x - width/2) / zoom;

I need

let worldX = (x - width/2)/zoom - dragPos.x

so it goes accordingly to my transformation order

    translate(width/2, height/2);
    translate(dragPos.x , dragPos.y);

So that is working now!
Anyway, Thanks a lot friend!! You are being of great help for me.