Jeff Molofee - NeHe's OpenGL Tutorials

Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

if (g_keys->keyDown[' '] && game) // Space Bar Being Pressed After Game Has Ended?

{

for (int loop=0; loop<30; loop++) // Loop Through 30 Objects

InitObject(loop); // Initialize Each Object

game=FALSE; // Set game (Game Over) To False

score=0; // Set score To 0

level=1; // Set level Back To 1

kills=0; // Zero Player Kills

miss=0; // Set miss (Missed Shots) To 0

}

The code below checks to see if the F1 key has been pressed. If F1 is being pressed, ToggleFullscreen will switch from windowed to fullscreen mode or fullscreen mode to windowed mode.

if (g_keys->keyDown[VK_F1]) // Is F1 Being Pressed?

{

ToggleFullscreen (g_window); // Toggle Fullscreen Mode

}

To create the illusion of rolling clouds and moving ground, we decrease roll by .00005f multiplied by the number of milliseconds that have passed. This keeps the clouds moving at the same speed on all systems (fast or slow).

We then set up a loop to loop through all of the objects on the screen. Level 1 has one object, level 10 has 10 objects, etc.

roll-=milliseconds*0.00005f; // Roll The Clouds

for (int loop=0; loop

{

We need to find out which way the object should be spinning. We do this by checking the value of rot. If rot equals 1, we need to spin the object clockwise. To do this, we decrease the value of spin. We decrease spin by 0.2f multiplied by value of loop plus the number of milliseconds that have passed. By using milliseconds the objects will rotate the same speed on all systems. Adding loop makes each NEW object spin a little faster than the last object. So object 2 will spin faster than object 1 and object 3 will spin faster than object 2.

if (object[loop].rot==1) // If Rotation Is Clockwise

object[loop].spin-=0.2f*(float(loop+milliseconds)); // Spin Clockwise

Next we check to see if rot equals 2. If rot equals 2, we need to spin counter clockwise. The only difference from the code above is that we are increasing the value of spin instead of decreasing it. This causes the object to spin in the opposite direction.

if (object[loop].rot==2) // If Rotation Is Counter Clockwise

object[loop].spin+=0.2f*(float(loop+milliseconds)); // Spin Counter Clockwise

Now for the movement code. We check the value of dir if it's equal to 1, we increase the objects x value based on the milliseconds passed multiplied by 0.012f. This moves the object right. Because we use milliseconds the objects should move the same speed on all systems.

if (object[loop].dir==1) // If Direction Is Right

object[loop].x+=0.012f*float(milliseconds); // Move Right

If dir equals 0, the object is moving left. We move the object left by decreasing the objects x value. Again we decrease x based on the amount of time that has passed in milliseconds multiplied by our fixed value of 0.012f.

if (object[loop].dir==0) // If Direction Is Left

object[loop].x-=0.012f*float(milliseconds); // Move Left

Only two more directions to watch for. This time we check to see if dir equals 2. If so, we increase the objects y value. This causes the object to move UP the screen. Keep in mind the positive y axis is at the top of the screen and the negative y axis is at the bottom. So increasing y moves from the bottom to the top. Again movement is based on time passed.

if (object[loop].dir==2) // If Direction Is Up

object[loop].y+=0.012f*float(milliseconds); // Move Up

The last direction our object can travel is down. If dir equals three, we want to move the object down the screen. We do this by increasing the objects y value based on the amount of time that has passed. Notice we move down slower than we move up. When an object is falling, our fixed falling rate is 0.0025f. When we move up, the fixed rate is 0.012f.

if (object[loop].dir==3) // If Direction Is Down

object[loop].y-=0.0025f*float(milliseconds); // Move Down

After moving our objects we have to check if they are still in view. The code below first checks to see where our object is on the screen. We can roughly calculate how far left an object can travel by taking the objects distance into the screen minus 15.0f (to make sure it's a little past the screen) and dividing it by 2. For those of you that don't already know… If you are 20 units into the screen, depending on the way you set up the perspective, you have roughly 10 units from the left of the screen to the center and 10 from the center to the right. so –20.0f(distance)-15.0f(extra padding)=-35.0f… divide that by 2 and you get –17.5f. That's roughly 7.5 units off the left side of the screen. Meaning our object is completely out of view.

Anyways… after making sure the object is far off the left side of the screen, we check to see if it was moving left (dir=0). If it's not moving left, we don't care if it's off the left side of the screen!

Finally, we check to see if the object was hit. If the object is off the left of the screen, it's travelling left and it wasn't hit, it's too late for the player to hit it. So we increase the value of miss. This lowers morale and increases the number of missed targets. We set the objects hit value to TRUE so the computer thinks it's been hit. This forces the object to self destruct (allowing us to give the object a new texture, directions, spin, etc).

// If We Are To Far Left, Direction Is Left And The Object Was Not Hit

if ((object[loop].x<(object[loop].distance-15.0f)/2.0f) && (object[loop].dir==0) && !object[loop].hit) {

miss+=1; // Increase miss (Missed Object)

object[loop].hit=TRUE; // Set hit To True To Manually Blow Up The Object

}

The following code does the exact same thing as the code above, but instead of checking to see if we've gone off the left side of the screen, we check to see if it's gone off the right side of the screen. We also check to make sure the object is moving right and not some other direction. If the object is off the screen, we increase the value of miss and self destruct the object by telling our program it's been hit.

// If We Are To Far Right, Direction Is Left And The Object Was Not Hit

if ((object[loop].x>-(object[loop].distance-15.0f)/2.0f) && (object[loop].dir==1) && !object[loop].hit) {

miss+=1; // Increase miss (Missed Object)

object[loop].hit=TRUE; // Set hit To True To Manually Blow Up The Object

}

The falling code is pretty straight forward. We check to see if the object has just about hit the ground. We don't want it to fall through the ground which is at –3.0f. Instead, we check to see if the object is below –2.0f. We then check to make sure the object is indeed falling (dir=3) and that the object has not yet been hit. If the object is below –2.0f on the y axis, we increase miss and set the objects hit variable to TRUE (causing it to self destruct as it hits the ground… nice effect).

// If We Are To Far Down, Direction Is Down And The Object Was Not Hit

if ((object[loop].y<-2.0f) && (object[loop].dir==3) && !object[loop].hit) {

miss+=1; // Increase miss (Missed Object)

object[loop].hit=TRUE; // Set hit To True To Manually Blow Up The Object

}

Unlike the previous code, the going up code is a little different. We don't want the object to go through the clouds! We check to see if the objects y variable is greater than 4.5f (close to the clouds). We also make sure the object is travelling up (dir=2). If the objects y value is greater than 4.5f, instead of destroying the object, we change it's direction. That way the object will quickly pop out of the ground (remember, it goes up faster than it comes down) and once it gets to high we change its direction so it starts to fall toward the ground.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «NeHe's OpenGL Tutorials»

Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Jeff Jacobson - Sleep Tight
Jeff Jacobson
Jeff Salyards - Veil of the Deserters
Jeff Salyards
Jeff LaSala - The Darkwood Mask
Jeff LaSala
Jeff Lindsay - Dexter's Final Cut
Jeff Lindsay
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «NeHe's OpenGL Tutorials»

Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x