在OpenGL ES中,如何将屏幕坐标转换为世界坐标?

时间:2021-03-18 21:16:52

This is for a 2D game so there are only an x and y axis. The game is in landscape mode on the iPhone. I wish to be able to set the screen x and y coordinates of where to render a texture.

这适用于2D游戏,因此只有x和y轴。 iPhone上的游戏采用横向模式。我希望能够设置渲染纹理的位置的屏幕x和y坐标。

1 个解决方案

#1


7  

If you're doing a 2D game, you can set up your projection and model-view matrices so that you don't need to convert at all:

如果您正在进行2D游戏,您可以设置投影和模型视图矩阵,这样您根本不需要进行转换:

// This goes in your init code somewhere
// Set up 480x320 orthographic projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-240.0f, 240.0f, -160.0f, 160.0f, -1.0f, 1.0f);

// Rotate into landscape mode
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(-90.0f, 0.0f, 1.0f, 0.0f);

This makes it so that world coordinates (-240, -160) maps to the top-left of the screen (bottom-left in landscape mode), (240, 160) maps to the bottom-right (top-right in landscape), etc. Since the iPhone's screen is 480x320, you won't need to convert between world and screen coordinates with your matrices set up thusly.

这使得世界坐标(-240,-160)映射到屏幕的左上角(横向模式中的左下角),(240,160)映射到右下角(横向右上角)因为iPhone的屏幕是480x320,所以你不需要在世界和屏幕坐标之间进行转换。

Of course, if you want to be able to move the camera, then you'll need to offset by the camera's location.

当然,如果你想移动相机,那么你需要偏移相机的位置。

#1


7  

If you're doing a 2D game, you can set up your projection and model-view matrices so that you don't need to convert at all:

如果您正在进行2D游戏,您可以设置投影和模型视图矩阵,这样您根本不需要进行转换:

// This goes in your init code somewhere
// Set up 480x320 orthographic projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-240.0f, 240.0f, -160.0f, 160.0f, -1.0f, 1.0f);

// Rotate into landscape mode
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(-90.0f, 0.0f, 1.0f, 0.0f);

This makes it so that world coordinates (-240, -160) maps to the top-left of the screen (bottom-left in landscape mode), (240, 160) maps to the bottom-right (top-right in landscape), etc. Since the iPhone's screen is 480x320, you won't need to convert between world and screen coordinates with your matrices set up thusly.

这使得世界坐标(-240,-160)映射到屏幕的左上角(横向模式中的左下角),(240,160)映射到右下角(横向右上角)因为iPhone的屏幕是480x320,所以你不需要在世界和屏幕坐标之间进行转换。

Of course, if you want to be able to move the camera, then you'll need to offset by the camera's location.

当然,如果你想移动相机,那么你需要偏移相机的位置。