Jeff Molofee - NeHe's OpenGL Tutorials
Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:NeHe's OpenGL Tutorials
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:3 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 60
- 1
- 2
- 3
- 4
- 5
NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
for (int loop=0; loop<95; loop++) // Loop Through All 95 Lists
{
float cx=float(loop%16)/16.0f; // X Position Of Current Character
float cy=float(loop/16)/8.0f; // Y Position Of Current Character
glNewList(base+loop,GL_COMPILE); // Start Building A List
glBegin(GL_QUADS); // Use A Quad For Each Character
glTexCoord2f(cx, 1.0f-cy-0.120f); glVertex2i(0,0); // Texture / Vertex Coord (Bottom Left)
glTexCoord2f(cx+0.0625f, 1.0f-cy-0.120f); glVertex2i(16,0); // Texutre / Vertex Coord (Bottom Right)
glTexCoord2f(cx+0.0625f, 1.0f-cy); glVertex2i(16,16); // Texture / Vertex Coord (Top Right)
glTexCoord2f(cx, 1.0f-cy); glVertex2i(0,16); // Texture / Vertex Coord (Top Left)
glEnd(); // Done Building Our Quad (Character)
glTranslated(10,0,0); // Move To The Right Of The Character
glEndList(); // Done Building The Display List
} // Loop Until All 256 Are Built
}
The printing code is the code is also from lesson 17, but has been modified to allow us to print the score, level and morale to the screen (variables that continually change).
GLvoid glPrint(GLint x, GLint y, const char *string, …) // Where The Printing Happens
{
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (string == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, string); // Parses The String For Variables
vsprintf(text, string, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
glBindTexture(GL_TEXTURE_2D, textures[9].texID); // Select Our Font Texture
glPushMatrix(); // Store The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glTranslated(x,y,0); // Position The Text (0,0 – Bottom Left)
glListBase(base-32); // Choose The Font Set
glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopMatrix(); // Restore The Old Projection Matrix
}
This code will be called later in the program by qsort. It compares the distance in two structures and return –1 if the first structures distance was less than the seconds structures distance, 1 if the first structures distance is greater than the second structures distance and 0 if the distance is the same in both structures.
int Compare(struct objects *elem1, struct objects *elem2) // Compare Function *** MSDN CODE MODIFIED FOR THIS TUT ***
{
if (elem1->distance < elem2->distance) // If First Structure distance Is Less Than The Second
return –1; // Return –1
else if (elem1->distance > elem2->distance) // If First Structure distance Is Greater Than The Second
return 1; // Return 1
else // Otherwise (If The distance Is Equal)
return 0; // Return 0
}
The InitObject() code is where we set up each object. We start off by setting rot to 1. This gives the object clockwise rotation. Then we set the explosion animation to frame 0 (we don't want the explosion to start halfway through the animation). Next we set hit to FALSE, meaning the object has not yet been hit or set to self destruct. To select an object texture, texid is assigned a random value from 0 to 4. Zero is the blueface texture and 4 is the vase texture. This gives us one of 5 random objects.
The variable distance will be a random number from –0.0f to –40.0f (4000/100 is 40). When we actually draw the object, we translate another 10 units into the screen. So when the object are drawn, they will be drawn from –10.0f to –50.0f units into the screen (not to close, and not too far). I divide the random number by 100.0f to get a more accurate floating point value.
After assigning a random distance, we then give the object a random y value. We don't want the object any lower than –1.5f, otherwise it will be under the ground, and we dont want the object any higher than 3.0f. So to stay in that range our random number can not be any higher than 4.5f (-1.5f+4.5f=3.0f).
To calculate the x position, we use some tricky math. We take our distance and we subtract 15.0f from it. Then we divide the result by 2 and subtract 5*level. Finally, we subtract a random amount from 0.0f to 5 multiplied by the current level. We subtract the 5*level and the random amount from 0.0f to 5*level so that our object appears further off the screen on higher levels. If we didn't, the objects would appear one after another, making it even more difficult to hit all the targets than it already is.
Finally we choose a random direction (dir) from 0 (left) to 1 (right).
To make things easier to understand in regards to the x position, I'll write out a quick example. Say our distance is –30.0f and the current level is 1: object[num].x=((-30.0f-15.0f)/2.0f)-(5*1)-float(rand()%(5*1));
object[num].x=(-45.0f/2.0f)-5-float(rand()%5);
object[num].x=(-22.5f)-5-{lets say 3.0f};
object[num].x=(-22.5f)-5-{3.0f};
object[num].x=-27.5f-{3.0f};
object[num].x=-30.5f;
Now keeping in mind that we move 10 units into the screen before we draw our objects, and the distance in the example above is –30.0f. it's safe to say our actual distance into the screen will be –40.0f. Using the perspective code in the NeHeGL.cpp file, it's safe to assume that if the distance is –40.0f, the far left edge of the screen will be –20.0f and the far right will be +20.0f. In the code above our x value is –22.5f (which would be JUST off the left side of the screen). We then subtract 5 and our random value of 3 which guarantees the object will start off the screen (at –30.5f) which means the object would have to move roughly 8 units to the right before it even appeared on the screen.
GLvoid InitObject(int num) // Initialize An Object
{
object[num].rot=1; // Clockwise Rotation
object[num].frame=0; // Reset The Explosion Frame To Zero
object[num].hit=FALSE; // Reset Object Has Been Hit Status To False
object[num].texid=rand()%5; // Assign A New Texture
object[num].distance=-(float(rand()%4001)/100.0f); // Random Distance
object[num].y=-1.5f+(float(rand()%451)/100.0f); // Random Y Position
// Random Starting X Position Based On Distance Of Object And Random Amount For A Delay (Positive Value)
object[num].x = ((object[num].distance-15.0f)/2.0f) - (5*level)-float(rand()%(5*level));
object[num].dir=(rand()%2); // Pick A Random Direction
Now we check to see which direction the object is going to be travelling. The code below checks to see if the object is moving left. If it is, we have to change the rotation so that the object is spinning counter clockwise. We do this by changing the value of rot to 2.
Our x value by default is going to be a negative number. However, the right side of the screen would be a positive value. So the last thing we do is negate the current x value. In english, we make the x value a positive value instead of a negative value.
if (object[num].dir==0) // Is Random Direction Right
{
object[num].rot=2; // Counter Clockwise Rotation
object[num].x=-object[num].x; // Start On The Left Side (Negative Value)
Интервал:
Закладка:
Похожие книги на «NeHe's OpenGL Tutorials»
Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.