[英]OpenGL Coordinate system confusion
也許我設置GLUT錯誤。 我希望頂點相對於像素大小。 現在,如果我創建一個六邊形,即使單位為6,它也會占據整個屏幕。
#include <iostream>
#include <stdlib.h> //Needed for "exit" function
#include <cmath>
//Include OpenGL header files, so that we can use OpenGL
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
//Called when a key is pressed
void handleKeypress(unsigned char key, //The key that was pressed
int x, int y) { //The current mouse coordinates
switch (key) {
case 27: //Escape key
exit(0); //Exit the program
}
}
//Initializes 3D rendering
void initRendering() {
//Makes 3D drawing work when something is in front of something else
glEnable(GL_DEPTH_TEST);
}
//Called when the window is resized
void handleResize(int w, int h) {
//Tell OpenGL how to convert from coordinates to pixel values
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
//Set the camera perspective
glLoadIdentity(); //Reset the camera
gluPerspective(45.0, //The camera angle
(double)w / (double)h, //The width-to-height ratio
1.0, //The near z clipping coordinate
200.0); //The far z clipping coordinate
}
//Draws the 3D scene
void drawScene() {
//Clear information from last draw
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); //Reset the drawing perspective
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_POLYGON); //Begin quadrilateral coordinates
//Trapezoid
glColor3f(255,0,0);
for(int i = 0; i < 6; ++i) {
glVertex2d(sin(i/6.0*2* 3.1415),
cos(i/6.0*2* 3.1415));
}
glEnd(); //End quadrilateral coordinates
glutSwapBuffers(); //Send the 3D scene to the screen
}
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(400, 400); //Set the window size
//Create the window
glutCreateWindow("Basic Shapes - videotutorialsrock.com");
initRendering(); //Initialize rendering
//Set handler functions for drawing, keypresses, and window resizes
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutMainLoop(); //Start the main loop. glutMainLoop doesn't return.
return 0; //This line is never reached
}
如何使坐標(0,0)
, (10,0)
, (10,10)
和(0,10)
定義一個從屏幕左上方開始的多邊形,其寬度為高度為10像素?
如果要以這種方式縮放對象,則應使用正交投影。
現在,從角度來看,事物不僅通過其大小縮放,而且通過其Z軸位置縮放。 因此,請使用此函數代替gluPerspective
:
gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);
該功能基本上定義了您可以看到的空間,就像一個大的矩形棱鏡。 這使遠處的事物看起來與近處的事物相同。
至於確切的縮放比例,它也將相對於視口大小發生變化。 為了使像素完全正確,您必須不斷更改投影,或保持視口大小不變。
為了使其以1:1的比例工作,如果您的視口是x
像素寬,則正交投影也應該是x
像素寬。
如果使用2D繪圖,則不想使用透視投影。 如果使用gluOrtho2D(0, window_width, window_height, 0);
設置攝像機 那么您應該得到想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.