План
Створення простого тривимірного зображення кадру гри. Основи.
Метод визначення швидкості роботи гри.
Додаткові можливості.
Система розробки: Pentium 150Mhz, 32M RAM, 1G HDD, S3 SVGA, Borland C++ 3.1
Мета: Створити гру, що зовнішньо схожа на Wolfenstein 3D
Методы: Гра створена за методом, що зветься Ray Casting (проведення променя) — процес зображення тривимірного світу за двовимірною інформацією. Ось основні принципи цього методу:
1. На основі двовимірної карти, що схожа на папір в клітинку, будується лабіринт, що складається з замальованих та чистих клітинок.
2. Мапа створена з квадратів фіксованого розміру (в нашому випадку — 64 x 64), що дозволяє кожному об’єкту (гравцю) пересуватися на 64 одиниці в будь-якому напрямі до переходу на інший квадрат. Весь лабіринт складається з таких квадратів, що утворюють двовимірний масив.
3. Гравець визначається як місце на цій мапі, що має три характеристики:
координату X
координату Y
кут зору
Так як ми знаємо, де знаходиться гравець та те, в який бік він дивиться, ми можемо взнати, що він бачить в цей момент. Для початку нам треба вирішити яке поле зору має гравець. Нехай це буде 60, для того щоб зображення було найбільш реалістичним. Це значить, що гравець буде бачити всі предмети та стіни на 30 ліворуч та на 30 праворуч.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
5. Тепер ми отримали поле зору, що включає в себе стіни попереду гравця при данному куті зору.
6. Ось що має бачити гравець в цьому випадку.
7. Так як же все ж таки отримати таке тривимірне зображення з двовимірної мапи? Просто вираховуючи висоту стін як функцію від відстані. Маючи поточні координати гравця, координати стіни та, використовуючи тригонометрію, ми можемо визначити відстань між гравцем та стіною. Проблема в тому, щоб виконати всі ці розрахунки настільки швидко, щоб гра виглядала реалістично. Але цим ми займемося пізніше. Зараз нехай спрацює простий метод визначення відстані до стіни. При цьому потрібно пам’ятати, що ми проводимо промінь для кожного стовпчика пікселей екрану, що для режиму VGA 13h (320x200x256) дає нам 320 стовпчиків по 200 пікселів. Тобто, 320 променів буде проведено щоб намалювати 1 кадр.
8. Почнемо з заповнення початкових значень для гравця. Як ми вже сказали, кожний квадрат має розміри 64x64 одиниці. Нехай гравець стоїть в клітинці (1, 1) десь на ѕ клітинки згори та на ј клітинки зліва. Значить координати гравця десь приблизно (80, 112) (64 + 64 * ј, 64 + 64 * ѕ). Початковий кут зору буде 0. Так як ми будемо використовувати тригонометричні функції з бібліотеки <math.h> мови C, ми будемо використовувати координатну систему, де кут збільшується за годинниковою стрілкою.
9. Тому, як було сказано в пункті 4, ми починаємо проводити промені від 30 зліва від нашого кута зору (=0) (або з 330) до 30 справа від нашого кута зору (або до 30). Можна побачити правильний трикутник від того місця де стоїть гравець до точки з кутом 330.
; ; ;
10. Зараз ми можемо намалювати (вигадану) лінію від гравця до якої-небудь точки на куті 330. Але наскільки ж довгою має бути ця лінія? Настільки, щоб можна було визначити що ми натрапили на стіну або вийшли за межі нашого лабіринту. Нехай наш лабіринт має розміри 10x8 (x*y). Тоді у нас 80 квадратів. Тоді максимальна ширина (довжина) нашого лабіринту —64 * 10 = 640 на 64 * 8 = 512. Максимальна відстань, на яку нам потрібно пускати промінь — , , що дорівнює 819.5999 або 820 одиниць. Що ж, 820 це максимальна відстань, на яку ми можемо пустити промінь, переглядаючи по дорозі чи не натрапили ми на стіну або чи не вийшли ми за межі лабіринту. Ми звели проведення променя до малювання лінії. А для малювання лінії у нас є алгоритм Брезенхама. Нам треба тільки визначити координати кінцевих точок лінії. Якщо ми маємо початкові координати гравця (X, Y), тоді використаємо вирази для точок кола щоб взнати кінцеві координати.
Використавши числа з пунктів 8 та 10 отримуємо:
що дає: . Передавши параметри (80, 112, 790, -298) в процедуру проведення лінії, що перевіряє зіткнення з стінами. Для кожної точки вздовж лінії ми визнячаємо координати на нашій карті так:
Поглянувши знову на малюнок 1 ми бачимо що наше перше зіткнення з стіною відбувається у клітинці (2, 0). Тепер визначимо відстань до цієї стіни. Назвемо точку перетину з стіною W, щоб не сплутати її з точкою кінця відрізка. Відстань визначається так: , . З малюнку видно, що стіна знаходиться десь в (128, 128) в квадраті (2, 0) тому: , з чого виплаває, що відстань = 50.596 або приблизно 51 одиниці. Знаючи відстань ми, заглянувши в таблицю висот, можемо взнати висоту стіни і намалювати одну горизонтальну лінію на екрані визначеної висоти. Продовжуємо цей процес для всіх колонок на екрані (320), де кожна колонка відповідає віддалі до стіни, і заповнюємо весь екран. Як ви мабуть і здогадуєтесь, ми не будемо зменшувати наш кут по цілому градусу, а по що дорівнює 0,1875. 320 стовпчиків по 0,1875 дає нашого поля зору.
Таблиця висот будується так: для кожної з можливих відстаней висота=відстань/С, де С — коефіцієнт, що вибирається пробним шляхом.
Так ми малюємо один кадр нашої гри. Він залежить від двох параметрів — координат гравця та його кута зору. Змінюючи ці параметри та перемальовуючи екран знову можна отримати те що бачить гравець з новими координатами та/або кутом зору. А самі зміни координат та кута відбуваються в залежності від тих клавіш, що їх натиснув гракець на клавіатурі, або від перевування мишки. Чим більше кадрів малювати за одиницю часу, тим більш плавною і реалістичною буде гра.
Коротше кажучи, ось основні кроки:
Візьміть кут зору гравця і відніміть 30 від нього щоб отримати напрям першого променя.
Вирахуйте координати кінцевої точки використовуючи початкові координати гравця, напрям променя та максимальну відстань, на яку проводиться промінь.
Використовуючи алгоритм лінії Брезенхама, в кожній точці лінії перевіряти, чи не втикнулися ми зі стіною і чи не вийшли ми за межі лабіринту. Якщо знайшли стіну, повернути координати (Wx, Wy) точки перетину.
Використувуючи координати грвця та координати перетину з стіною визначити відстань до стіни.
Використувуючи відстань, визначити з таблиці висот висоту стіни яку треба намалювати.
Додати 0,1875 до кута проведення променя і знову пройти пункти 1-6 доки не намалюємо всі 320 ліній екрану.
11. Описаний вище алгоритм дає більш-менш нормальний результат, але має декілька недоліків:
Швидкість. Проведення 320 ліній для кожного кадру просто дуже повільно. На екрані може бути видно як перемальовується кожен кадр зліва направо.
Перетини. Немає простого способу визначити з якою саме чистиною стіни перетнувся наш промінь, а тому важко на стіни накласти текстуру.
Для точнішого визначення швидкості роботи описаного алгоритму (в кадрах за секунду), були написані відповідні процедури. Ось основна схема визначення кількості кадрів за секунду.
long getTime() {
return peek(0, 0x46E)*65535+peek(0, 0x46C);
int TimeCounter=0;
void main(void) {
long RememberTheTime=getTime();
int FramesPerSecond=0;
while (TRUE) {
TimeCounter++;
if (getTime()-RememberTheTime>=18) {
FramesPerSecond=TimeCounter;
TimeCounter=0;
RememberTheTime=getTime();
}
}
}
Функція getTime() повертає поточний час у вигладі довгого цілого. Це число збільшується на одиницю приблизно 18 разів на секунду. TimeCounter показує скільки разів виконався цикл. У функції main() організован основний цикл програми, що збільшує TimeCounter на одиницю. На початку роботи програми час, що повертається функцією GetTime запам’ятовується у змінній RememberTheTime. Але якщо в ході роботи циклу пройшла 1 секунда, то FramesPerSecond буде мати значення кількості проходів циклу за секунду. При умові що за один цикл програми малюється один кадр, то FramesPerSecond можна вважати кількістю кадрів за секунду.
А ось що можна зробити для покращення та прискорення цієї гри.
В першу чергу потрібно звільнитися від чисел з точкою, що плаває. Використавши числа з фіксованою точкою ми прискоримо весь алгоритм. Число з фіксованою точкою приблизно дорівнює числу з плаваючою точкою побітово зсунутим дещо вліво, щоб зберігати дробову частину. a = long( (float)b << 8). Такі числа можна складати та віднімати без перетворень. Щоб ділити та множити потрібно виконати побітові зсуви — (a >> 8) * (b >>8).
По-друге, потрібно всі значення, які можна, вирахувати заздалегідь і помістити в змінні та масиви. Наприклад значення сінусів та косінусів можна занести в таблицю з 360 елементів, що відповідають кожному з 360.
Накладання текстури відбувається за методом інтерполяції. Знаючи верхню та нижню точки, можна пройти в циклі по всім точкам від верхньої до нижньої і взнати відповідні точки в текстурі. Але більш докладне пояснення виходить за рамки даного документу.
Робота з монстрами майже нічим не відрізняється від роботи з самим гравцем. Він має координати свого положення і кут зору. Переміщується до гравця якщо має досить енергії і стріляє через рандомізований проміжок часу. Якщо енергії недостатньо, втікає.
Список літератури
1. Lary Myers. Animation Construction Kit 3D
2. Sebastien Loisel. Zed3D. A compact reference for 3D computer graphics.
Дейв Робертс. Программирование игрушек. Основы.
Mark Feldman. Brezenham’s Line and Circle Algorithms.
Sebastien Loisel. A tutorial for 2D and 3D vector and texture mapped graphics. Version 0.60
Chris. Egerter. Texture mapped polygons.
Другие работы по теме:
Do Fairy Tales Loes There Mean Essay
, Research Paper Comparison Paper One chilly night you decide to pull out your old book of fairytales. As you dust off the cover you start reading along, and as you finish the tale. You re struck with a large volt of curiosity, you realize that it was not the same as the tale you were told when you were little. You reread the authors name and see it is the Charles Perrualt.
The 3 Pigz Life Story Essay Research
Paper THE THREE PIGS LIFE STORY THE LATEST Once upon a time there lived a wild mad pig who once fell in love with the most intelligent hogs on this side of the stars. These two bores were the hottest couple in the village of Pigsburg far, far, away. They were soon to be married and had TRIPLETS. The mother pig named them Piglet, Porky, and Wilbur.
3Rd Pig
’s Version Essay, Research Paper Where should I begin? I guess that I will start with the construction of my house. Winter was coming soon, so my two brothers and I decided to make houses for shelter from the cold. I, being the smart one of the group, decided to make my house out of trusty brick and mortar. I knew that this winter would be a snow filled because of El Ni o and only something as strong as brick would keep me warm and safe.
Napster Essay Research Paper Ruling could doom
Napster Essay, Research Paper Ruling could doom Napster A federal court ruled yesterday that Napster must stop allowing users to swap copyrighted music. Napster officials said they would keep operating while they fought in court. Napster was created by a teenager in 1999. Napster’s software lets computer users trade audio files by connecting with one another.
The Beauty Myth Essay Research Paper The
The Beauty Myth Essay, Research Paper The Beauty Myth, published by Doubleday in New York City, hit the shelves in 1992. Naomi Wolf wrote this 348-page book. Wolf attended Yale University and New College, Oxford University, where she was a Rhodes Scholar. Her essays have been printed in many well-known magazines and newspapers, including Esquire and the New York Times.
Gray Wolves In Yellowstone Essay Research Paper
The reintroduction of Gray Wolves into Yellowstone has had many positive affects such as controlling the populations of large game and taking out the small week stupid ones. Some farmers complain about them killing cattle but who cares what they think.
The Three Little Pigs Essay Research Paper
The Three Little Pigs When reading Text Book we learn about Intertextuality, which is the technical term for a relationship between any form of literature that produces another in relation to its original. Such as the resent movie remake of the William Shakespeare s Taming of the Shrew called 10 Things I Hate About You.
The Crossing Essay Research Paper The Crossing
The Crossing Essay, Research Paper The Crossing In Cormac McCarthy s novel The Crossing, there is a dramatic sequence described by the narrator. The author uses many different techniques to convey the impact of the experience on the narrator. Some of these such techniques are: repetition, diction, and simile.
Reintroduction Of Wolves Essay Research Paper The
Reintroduction Of Wolves Essay, Research Paper The Reintroduction of Wolves In my opinion, wolves should be able to live and survive in the wild. Ranchers do need to consider that wolves have a major
The Sea Wolf Essay Research Paper The
The Sea Wolf Essay, Research Paper The crew of the seal hunting ship the Ghost stood in disbelief as they gazed upon their recently departed first mate. Then a most unusual thing occurred. The captain began yelling at the dead man like a raging storm. Oaths rolled from his lips in a continuous stream. And they were not nice and thoughtful words or mere expressions of indecency.
Comparitive Essay Essay Research Paper There are
Comparitive Essay Essay, Research Paper There are many stories of survival. When I think of survival I think of two things, The movie, Never Cry Wolf, and the story, When the Legends Die. These two are stories of men who survived in the wild after many obtacles. They were both very different but they were still the same.
Christa Wolf Essay Research Paper Wolf Christa
Christa Wolf Essay, Research Paper Wolf, Christa (1929- ), German novelist and essayist, known for her novels about Germany during World War II (1939-1945). Born Christa Ihlenfeld in Landsberg an der Warthe (now Gorz w Wielkopolski, Poland), she studied at the Universities of Leipzig and Jena from 1949 to 1953.
White Fang Essay Research Paper Two outdoorsmen
White Fang Essay, Research Paper Two outdoorsmen are out in the wild of the north. They are on a mission to deliver the body and coffin of a famous person. Their dogs disappear as they are entised by a she-wolf and eaten by the rest of the pack. They only have
Grey Wolves Essay Research Paper The gray
Grey Wolves Essay, Research Paper The gray wolf has a larger natural distribution than any other mammal except humans. It formerly inhabited all of North America from Alaska and Arctic Canada south to central Mexico and was found in Europe and Asia southward to the Mediterranean Sea, the Arabian Peninsula, and parts of India and China.
The Grey Wolf Essay Research Paper Scientific
The Grey Wolf Essay, Research Paper Scientific name -Kingdom-Animalia, Phylum- Chordate, Class- Mammilla, Order- Carnivorous, Family- Canida, Genus- Canis, Species- lupusDescription -Canis lupus’s’ height ranges from about 21-38 inches and three and a half feet long. Their weight ranges from 20 -172 pounds.
Wolves Essay Research Paper The grey wolf
Wolves Essay, Research Paper The grey wolf is one of approximately 35 species belonging to the family Canidae, which includes the coyote, jackal, fox, and the dog. This family is believed to have originated in North America 38 to 54 million years ago during the Eocene Epoch. Two species- and a varying number of subspecies- of wolves are recognized: the grey, or timber, wolf, once widely distributed in North America, Europe, and Asia; and the red wolf, which now occurs only in Texas and the south-eastern United States.
Little Red Mountain Biker Essay Research Paper
Little Red Mountain Biker and the Big, Fat Motorist One day Little Red Mountain Biker was out on a little fitness ride to her grandmother’s house in the country, about 20 miles away. When she was nearly there, when she found herself being harassed by an overweight wolf in a sports car. Recognizing the danger of being hit by his car or being attacked in the lonely woods, she suggested to him on one of his passes that he meet her at Grandma’s house, the last house on the road at the edge of the mountain, where “no one is home.”
Never Cry Wolf Essay Research Paper In
Never Cry Wolf Essay, Research Paper In this essay I will cover main differences between the book and the movie giving my opinion of why these changes were necessary in the making of this
John Minnie And Petie A Love Triangle
Essay, Research Paper Karen Rayne Mrs. Wolf English 102.004 2 March 2001 John, Minnie, and Petie, A Love Triangle: Comedy and Tragedy in Susan Glaspell’s Trifles
Sea Wolf Essay Research Paper Sea WolfWolf
Sea Wolf Essay, Research Paper Sea Wolf Wolf Larsen was a character in the book who never made it all the way through the book, but he tried very hard. He was a very strong, brutal man
Wolf Spiders Essay Research Paper Wolf spiders
Wolf Spiders Essay, Research Paper Wolf spiders are a group of ground-dwelling hunting spiders. There are more than 2000 types of wolf spiders. They range from 2mm to 40mm. Some wolf spiders can even walk on the water of a pond. They can walk or run while chasing after it?s prey. They use their front legs to catch their prey, and then they bite and crush the prey with their powerful jaws.
The Need For Honesty Essay Research Paper
The Need for People Honesty. Everyones heard the tale of the Boy who cried Wolf right? Sure, shepherd boy thinks he’s funny, makes a fuss about imaginary wolfs, villagers come running – no wolf. Then when wolfs actually do come, he yells and screams, yet villagers weren’t about to play his game again, his sheep get nailed by the wolves.
Aeschylus Agamemnon Essay Research Paper Aeschylus Agamemnon
Aeschylus? Agamemnon Essay, Research Paper Aeschylus? Agamemnon tells the story of what happened to the Greek hero Agamemnon when he returns home to Myceneae. Cassandra, daughter of Priam, king of Troy, plays a powerful figure in the play because she foretells the doom of Agamemnon and of herself through visions of a curse upon his household. ?Agamemnon, you will see him dead?, (p.544, l. 1262) Cassandra tells the reader.
Wolf Population Essay Research Paper Wolf Population
Wolf Population Essay, Research Paper Wolf Population The population of humans directly affects the population of canis lupus (gray wolf) and other wolf species. Some people think wolves are blood-thirsty, savage man killers, but in actuality, the wolf is usually more afraid of us. One of the many things that wolves have been compared to is the lions of Africa (Wexo 6).
Creative Writing The Story Of The Three
Little Pigs Essay, Research Paper Creative Writing: The Story of the Three Little Pigs 1. Upon a time there lived a homely hog woman, and her three straplings.
Mexican Grey Wolf Essay Research Paper The
Mexican Grey Wolf Essay, Research Paper The Mexican Grey Wolf by Until recently, the Mexican Grey Wolf roamed the Chihuahan and Sonaran deserts from central Mexico to western Texas, central Arizona and New Mexico. By 1900 the decrease in prey the wolves hunted and fed on, such as deer and elk, reduced greatly.
Werewolf Essay Research Paper TOP TEN REASONS
Werewolf Essay, Research Paper TOP TEN REASONS YOU MIGHT BE TURNING INTO A WOLF. #1. Having hairy palms is considered a sure sign of being a werewolf. #2. Rough palms are also considered to be a sign.
The Report Essay Research Paper Each night
The Report Essay, Research Paper Each night a female half wolf half dog would seduce a dog away and allow the pack to kill him. This killing of the dogs lasted until there were 3 dogs remaining. One man tried to save a 4th dog that was being killed by the wolves and ended up getting killed also. From then on the wolves closed in on the camp of the remaining man and 2 dogs.
The Boy Who Cried Wolf Essay Research
Paper The Boy Who Cried Wolf There once was a boy who tended his father?s sheep. The father was very protective about his boy and his sheep. He gave his son a horn and told him that if the sheep or himself were ever in trouble to blow the horn as loud as he could and the men of the village would come right away to help in the emergency.
Tevya And His First Daughter Essay Research
Paper Tevya and His First Daughter Tevya and His First Daughter is about a poor dairyman, Tevya, and his daughter Tzeitl, who is in an arranged marriage that she does not want to be in.