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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
}
Now we check the texid to find out what object the computer has randomly picked. If texid is equal to 0, the computer has picked the Blueface object. The blueface guys always roll across the ground. To make sure they start off at ground level, we manually set the y value to –2.0f.
if (object[num].texid==0) // Blue Face
object[num].y=-2.0f; // Always Rolling On The Ground
Next we check to see if texid is 1. If so, the computer has selected the Bucket. The bucket doesn't travel from left to right, it falls from the sky. The first thing we have to do is set dir to 3. This tells the computer that our bucket is falling or moving down.
Our initial code assumes the object will be travelling from left to right. Because the bucket is falling down, we have to give it a new random x value. If we didn't, the bucket would never be visible. It would fall either far off the left side of the screen or far off the right side of the screen. To assign a new value we randomly choose a value based on the distance into the screen. Instead of subtracting 15, we only subtract 10. This gives us a little less range, and keeps the object ON the screen instead of off the side of the screen. Assuming our distance was –30.0f, we would end up with a random value from 0.0f to 40.0f. If you're asking yourself, why from 0.0f to 40.0f? Shouldn't it be from 0.0f to –40.0f? The answer is easy. The rand() function always returns a positive number. So whatever number we get back will be a positive value. Anyways… back to the story. So we have a positive number from 0.0f to 40.0f. We then add the distance (a negative value) minus 10.0f divided by 2. As an example… assuming the random value returned is say 15 and the distance is –30.0f:
object[num].x = float(rand()%int(-30.0f-10.0f))+((-30.0f-10.0f)/2.0f);
object[num].x = float(rand()%int(-40.0f)+(-40.0f)/2.0f);
object[num].x = float(15 {assuming 15 was returned))+(-20.0f);
object[num].x = 15.0f-20.0f;
object[num].x = -5.0f;
The last thing we have to do is set the y value. We want the bucket to drop from the sky. We don't want it falling through the clouds though. So we set the y value to 4.5f. Just a little below the clouds.
if (object[num].texid==1) // Bucket
{
object[num].dir=3; // Falling Down
object[num].x = float(rand()%int(object[num].distance-10.0f)) + ((object[num].distance-10.0f)/2.0f);
object[num].y=4.5f; // Random X, Start At Top Of The Screen
}
We want the target to pop out of the ground and up into the air. We check to make sure the object is indeed a target (texid is 2). If so, we set the direction (dir) to 2 (up). We use the exact same code as above to get a random x location.
We don't want the target to start above ground. So we set it's initial y value to –3.0f (under the ground). We then subtract a random value from 0.0f to 5 multiplied by the current level. We do this so that the target doesn't INSTANTLY appear. On higher levels we want a delay before the target appears. Without a delay, the targets would pop out one after another, giving you very little time to hit them.
if (object[num].texid==2) // Target
{
object[num].dir=2; // Start Off Flying Up
object[num].x = float(rand()%int(object[num].distance-10.0f)) + ((object[num].distance-10.0f)/2.0f);
object[num].y=-3.0f-float(rand()%(5*level)); // Random X, Start Under Ground + Random Value
}
All of the other objects travel from left to right, so there is no need to assign any values to the remaining objects. They should work just fine with the random values they were assigned.
Now for the fun stuff! "For the alpha blending technique to work correctly, the transparent primitives must be drawn in back to front order and must not intersect" . When drawing alpha blended objects, it is very important that objects in the distance are drawn first, and objects up close are drawn last.
The reason is simple… The Z buffer prevents OpenGL from drawing pixels that are behind things that have already been drawn. So what ends up happening is objects drawn behind transparent objects do not show up. What you end up seeing is a square shape around overlapping objects… Not pretty!
We already know the depth of each object. So after initializing a new object, we can get around this problem by sorting the objects using the qsort function (quick sort). By sorting the objects, we can be sure that the first object drawn is the object furthest away. That way when we draw the objects, starting at the first object, the objects in the distance will be drawn first. Objects that are closer (drawn later) will see the previously drawn objects behind them, and will blend properly!
As noted in the line comments I found this code in the MSDN after searching the net for hours looking for a solution. It works good and allows you to sort entire structures. qsort takes 4 parameters. The first parameter points to the object array (the array to be sorted). The second parameter is the number of arrays we want to sort… of course we want to sort through all the object currently being displayed (which is level). The third parameter specifies the size of our objects structure and the fourth parameter points to our Compare() function.
There is probably a better way to sort structures, but qsort() works… It's quick, convenient and easy to use!
It's important to note, that if you wanted to use the glAlphaFunc() and glEnable(GL_ALPHA_TEST), sorting is not necessary. However, using the Alpha Function you are restricted to completely transparent or completely opaque blending, there is no in between. Sorting and using the Blendfunc() is a little more work, but it allows for semi-transparent objects.
// Sort Objects By Distance: Beginning Address Of Our object Array *** MSDN CODE MODIFIED FOR THIS TUT ***
// Number Of Elements To Sort
// Size Of Each Element
// Pointer To Our Compare Function
qsort((void *) &object, level, sizeof(struct objects), (compfn)Compare );
}
The init code is same as always. The first two lines grab information about our window and our keyboard handler. We then use srand() to create a more random game based on the time. After that we load our TGA images and convert them to textures using LoadTGA(). The first 5 images are objects that will streak across the screen. Explode is our explosion animation, ground and sky make up the background scene, crosshair is the crosshair you see on the screen representing your current mouse location, and finally, the font image is the font used to display the score, title, and morale. If any of the images fail to load FALSE is returned, and the program shuts down. It's important to note that this base code will not return an INIT FAILED error message.
BOOL Initialize (GL_Window* window, Keys* keys) // Any OpenGL Initialization Goes Here
{
g_window = window;
g_keys = keys;
srand((unsigned)time(NULL)); // Randomize Things
if ((!LoadTGA(&textures[0], "Data/BlueFace.tga")) || // Load The BlueFace Texture
(!LoadTGA(&textures[1], "Data/Bucket.tga")) || // Load The Bucket Texture
(!LoadTGA(&textures[2], "Data/Target.tga")) || // Load The Target Texture
(!LoadTGA(&textures[3], "Data/Coke.tga")) || // Load The Coke Texture
(!LoadTGA(&textures[4], "Data/Vase.tga")) || // Load The Vase Texture
(!LoadTGA(&textures[5], "Data/Explode.tga")) || // Load The Explosion Texture
Интервал:
Закладка:
Похожие книги на «NeHe's OpenGL Tutorials»
Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.