Translate mouseCoordinates


#1

hello!
its possible to translate mouseCoordinates?

in processing is a librarie call MouseTransformed. is any similar in ofx?

i want to translate mouseCoordinates to different objects positions to make a 2Dmap of a world. thanks!


#2

What do you mean by translate? Mouse coordinates are simple x and y coordinates, you can always add/subtract with those to get translated coordinates, or multiply it with a translation matrix.


#3

I want to check mouse intersection with multiples ellipses, drag it and move it. also i want to scale the map and get with the mouse the position in the world.


#4

Hi,
I think I just replied to something similar here.

If you draw an object like that…

ofPushMatrix() ;
ofTranslate( x, y );
ofRotateRad( angle );
ofScale( scale, scale );
ofTranslate( - anchorX, - anchorY );
// draw something. for example:
img.draw( 0.f, 0.f );
ofPopMatrix() ;

… the transformation matrix is:

glm::mat4 mat ;
mat = glm::translate( mat, glm::vec3( x, y, 0.f ) ) ;
mat = glm::rotate( mat, angle, glm::vec3( 0.f, 0.f, 1.f ) ) ;
mat = glm::scale( mat, glm::vec3( scaleX, scaleY, 1.f ) ) ;
mat = glm::translate( mat, glm::vec3( -anchorX, -anchorY, 0.f ) ) ;

This means that you’ve got the same drawing with:

ofPushMatrix() ;
ofMultMatrix( mat ) ;
// draw something. for example:
img.draw( 0.f, 0.f );
ofPopMatrix() ;

You can use this matrix to translate coordinates from the global coordinates system (the OF window) to the local object coordinates system (the image), and vice versa.

Local to global:
To compute were the point (10,50) of the image is drawn to the screen, do:

glm::vec4 p( 10.f, 50.f, 0.f, 1.f );
p = mat * p;
cout << "The point is displayed at position x=" << p.x << " and y=" << p.y << endl;

Global to local:
To compute which point in the image is at the screen position (300,400) do:

glm::vec4 p( 300.f, 400.f, 0.f, 1.f ) ;
p = glm::inverse( mat ) * p ;

Application exemple: find if the mouse is over an image

glm::mat4 mat ;
mat = glm::translate( mat, glm::vec3( x, y, 0.f ) ) ;
mat = glm::rotate( mat, angle, glm::vec3( 0.f, 0.f, 1.f ) ) ;
mat = glm::scale( mat, glm::vec3( scaleX, scaleY, 1.f ) ) ;
mat = glm::translate( mat, glm::vec3( -anchorX, -anchorY, 0.f ) ) ;

ofPushMatrix() ;
ofMultMatrix( mat ) ;
img.draw( 0.f, 0.f );
ofPopMatrix() ;

glm::vec4 globalMouse( ofGetMouseX(), ofGetMouseY(), 0.f, 1.f ) ;
glm::vec4 localMouse = glm::inverse( mat ) * globalMouse ;

ofRectangle rect( 0.f, 0.f, img.getWidth(), img.getHeight() );
if( rect.inside( localMouse.x, localMouse.y ) )
    cout << "Mouse is over the image" << endl;