[英]Java LWJGL OpenGL convert 3d point to 2d point
I'm trying to convert a 3d point in OpenGL to a 2d point on screen to render a healthbar for a little game I'm writing. 我正在尝试将OpenGL中的3d点转换为屏幕上的2d点,以渲染我正在编写的小游戏的健康栏。 However, I'm having some trouble retrieving the x coordinate of where to draw the healthbar.
但是,我在检索在何处绘制运行状况栏的x坐标时遇到了一些麻烦。 Basically, the healthbar must appear to be above a player, but must always have the same width/height relative to the screen.
基本上,运行状况栏必须看起来在播放器上方,但相对于屏幕必须始终具有相同的宽度/高度。
I tweaked a snippet of code I found from the accepted answer at Convert a 3D location to a 2D on-screen point. 我对从“ 将3D位置转换为2D屏幕点”中的可接受答案中找到的代码进行了调整。 (XYZ => XY) and I now have this
(XYZ => XY) ,我现在有了这个
public static int[] getScreenCoords(double x, double y, double z) {
FloatBuffer screenCoords = BufferUtils.createFloatBuffer(4);
IntBuffer viewport = BufferUtils.createIntBuffer(16);
FloatBuffer modelView = BufferUtils.createFloatBuffer(16);
FloatBuffer projection = BufferUtils.createFloatBuffer(16);
// int[] screenCoords = new double[4];
// int[] viewport = new int[4];
// double[] modelView = new double[16];
// double[] projection = new double[16];
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, modelView);
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);
boolean result = GLU.gluProject((float) x, (float) y, (float) z, modelView, projection, viewport, screenCoords);
if (result) {
return new int[] { (int) screenCoords.get(3), (int) screenCoords.get(1) };
}
return null;
}
It seems to work fine with the y coordinate, however, x always returns 0 no matter what the angle is. 似乎在y坐标下工作正常,但是,无论角度是多少,x始终返回0。
Many thanks in advance! 提前谢谢了!
screenCoords.get(3)
应该是screenCoords.get(0)
因为x位置存储在索引0中。实际上,您还只需要screenCoords
的容量为3个浮点数,而不是4个浮点数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.