views:

152

answers:

2

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...

+1  A: 

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 rotation will do the trick.

In general, you'll want to represent your transformation and its inverse as 3x3 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:

A = TA
A^-1 = A^-1 T^-1
+1  A: 

This is because the translation is done before the rotation. Let me explain this a little bit:

O=====>     (translate X)
      |     (translate Y)
      |
      x     (location)

When you rotate this object, you'll rotate the translations with it:

      O     
      |     
      |     (translate X)
      |
      |
   x==<     (translate Y & location)

To solve this; you should first rotate the object, when it's in it's origin, and then translate.

Rotating the object probably will also rotate the translation of that object (built-in), so you'll have to reverse the "translation", so it'll get at the correct point, but with correct rotation.

translate ---> rotate ---> inverse-translate

To do this;

x = x * cos(-rot) - y * sin(-rot)
y = x * sin(-rot) + y * cos(-rot)

Where rot is in radians.

Pindatjuh