How would you go about mapping mouse coordinates to world coordinates in a 2d context?
For example, you have an image which you can drag. Next, you apply a rotation to that image and redraw it. Now when you drag the image it does not get translated correctly. For example after rotating 90 degrees, dragging up would cause the image to translate to the right.
Any ideas?
Currently attempting to rotate the mouse coordinates like so:
mouseX = ((mouseX*Math.cos(rotation*180/Math.PI))-(mouseY*Math.sin(rotation*180/Math.PI))),
mouseY = ((mouseX*Math.sin(rotation*180/Math.PI))+(mouseY*Math.cos(rotation*180/Math.PI)))
But this doesn’t seem to be working…
You’ve got some image that lives in world coordinates, and you’re applying an affine transformation (composition of rotations, translations, and scaling) to it to get what it looks like on the screen:
World ——-[affine transformation]——-> Screen
Now if you want to map something that’s in screen coordinates (for instance, mouse cursor position) to world coordinates, you need to use the inverse of that affine transformation.
If your transformation is just a rotation, as in your code snippet, negative
rotationwill do the trick.In general, you’ll want to represent your transformation and its inverse as 3×3 matrices A and A^-1. If W and S are world and screen affine coordinates, you have
S = AW and W = A^1 S.
To add on another transformation T to A, multiply A on the left by T and A^-1 on the right by T^-1: