Android OpenGL ES: Normalized MotionEvent Coordinate

I am trying to take a touch event and move the figure to where the touch event is moving.

public boolean onTouchEvent(MotionEvent e) {
    mRenderer.setPosition(e.getX(), e.getY());

    return true;
}

The problem is that the coordinates that I get from MotionEvent are the location of the screen in pixels, not the normalized coordinates [-1, 1]. How to convert screen coordinates to normalized coordinates? Thanks in advance!

+4
source share
1 answer
    float x = e.getX();
    float y = e.getY();
    float screenWidth;
    float screenHeight;

    float sceneX = (x/screenWidth)*2.0f - 1.0f;
    float sceneY = (y/screenHeight)*-2.0f + 1.0f; //if bottom is at -1. Otherwise same as X

To add more general code:

 /*
 Source and target represent the 2 coordinate systems you want to translate points between.
 For this question the source is some UI view in which top left corner is at (0,0) and bottom right is at (screenWidth, screenHeight)
 and destination is an openGL buffer where the parameters are the same as put in "glOrtho", in common cases (-1,1) and (1,-1).
 */
float sourceTopLeftX;
float sourceTopLeftY;
float sourceBottomRightX;
float sourceBottomRightY;

float targetTopLeftX;
float targetTopLeftY;
float targetBottomRightX;
float targetBottomRightY;

//the point you want to translate to another system
    float inputX;
    float inputY;
//result
    float outputX;
    float outputY;

outputX = targetTopLeftX + ((inputX - sourceTopLeftX) / (sourceBottomRightX-sourceTopLeftX))*(targetBottomRightX-targetTopLeftX);
outputY = targetTopLeftY + ((inputY - sourceTopLeftY) / (sourceBottomRightY-sourceTopLeftY))*(targetBottomRightY-targetTopLeftY);

N- ( 3D Z, X Y). , 2 , , , .       sourceTopLeftX!= sourceBottomRightX

+4

Source: https://habr.com/ru/post/1533083/


All Articles