I have an odd situation where I know the position of an item on a mouse click and I know the panning state of a 2D camera pointing at it.

So what I do is render an object at the point in which the mouse was clicked and offset the position by the panning difference since the original mouse click.

This works fine until zooming in or out.

I've tried a few ideas to account for the zooming and all have failed:

    const [cameraPos, setCameraPos] = React.useState<{ k: number, x: number, y: number }>({ x: 0, y: 0, k: 1 })
const [cameraPosOnSelect, setCameraPosOnSelect] = React.useState<{ k: number, x: number, y: number }>({ x: 0, y: 0, k: 1 })
const [mousePos, setMousePos] = React.useState({ x: 0, y: 0 })

let tipPos = { ...mousePos };
let scaleDif = cameraPos.k - cameraPosOnSelect.k;

let offsetAmount = {
    x: (cameraPos.x - cameraPosOnSelect.x),
    y: (cameraPos.y - cameraPosOnSelect.y)

tipPos.x += offsetAmount.x;
tipPos.y += offsetAmount.y;

tipPos.x += offsetAmount.x * scaleDif;
tipPos.x += offsetAmount.y * scaleDif;

Where tipPos is ultimately the position the item is rendered.

I tried applying a scale dif but that didn't work.

  • \$\begingroup\$ Are you updating the scale factor and offset when the camera pans and scales or just onclick? Also, I see tipPos.x += offsetAmount.x * scaleDif; but you don't seem to be modifying the width or height. What exactly is happening with and without the scale dif? It's just difficult to see exactly what is and isn't behaving properly from your snippet. \$\endgroup\$ – dandeto Oct 11 '19 at 4:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.