Higher-Order Fun

Game Design & Game Programming

Math for Game Programmers 05 – Vector Cheat Sheet

This is the long due fifth article in this series. If you aren’t comfortable with vectors, you might want to take a look at the first four articles in this series before: Introduction, Vectors 101, Geometrical Representation of Vectors, Operations on Vectors.

This cheat sheet will list several common geometrical problems found in games, and how to solve them with vector math.

Complete list of basic vector operations

But first, a little review.

For this, I assume that you have a vector class readily available. This is mostly 2D-focused, but everything works the same for 3D, except for differences concerning vector product, which I will assume to return just a scalar in the 2D case, representing the “z” axis. Any case that only applies to 2D or 3D will be pointed out.

Strictly speaking, a point is not a vector – but a vector can be used to represent the distance from the origin (0, 0) to the point, and so, it is perfectly reasonable to just use vectors to represent positions as if they were points.

I expect the class to give you access to each of the components, and to the following operations (using C++ style notation, including operator overloading – but it should be easy to translate to any other language of your choice). If a given operation is not available, you can still do it manually, either by extending the class or creating a “VectorUtils” class. The examples below are usually for 2D vectors – but 3D is usually simply a matter of adding the z coordinate following the pattern of x and y.

  • Vector2f operator+(Vector2f vec): Returns the sum of the two vectors. (In a language without operator overloading, this will probably be called add(). Similarly for the next few ones.)
    a + b = Vector2f(a.x + b.x, a.y + b.y);
  • Vector2f operator-(Vector2f vec): Returns the difference between the two vectors.
    a – b = Vector2f(a.x – b.x, a.y – b.y);
  • Vector2f operator*(Vector2f vec): Returns the component-wise multiplication of the vectors.
    a * b = Vector2f(a.x * b.x, a.y * b.y);
  • Vector2f operator/(Vector2f vec): Returns the component-wise division of the vectors.
    a / b = Vector2f(a.x / b.x, a.y / b.y);
  • Vector2f operator*(float scalar): Returns the vector with all components multiplied by the scalar parameter.
    a * s = Vector2f(a.x * s, a.y * s);
    s * a = Vector2f(a.x * s, a.y * s);
  • Vector2f operator/(float scalar): Returns the vector with all components divided by the scalar parameter.
    a / s = Vector2f(a.x / s, a.y / s);
  • float dot(Vector2f vec): Returns the dot product between the two vectors.
    a.dot(b) = a.x * b.x + a.y * b.y;
  • float cross(Vector2f vec): (2D case) Returns the z component of the cross product of the two vectors augmented to 3D.
    a.cross(b) = a.x * b.y – a.y * b.x;
  • Vector3f cross(Vector3f vec): (3D case) Returns the cross product of the two vectors.
    a.cross(b) = Vector3f(a.y * b.z – a.z * b.y, a.z*b.x – a.x*b.z, a.x*b.y – a.y*b.x);
  • float length(): Returns the length of the vector.
    a.length() = sqrt(a.x * a.x + a.y * a.y);
  • float squaredLength(): Returns the square of the length of the vector. Useful when you just want to compare two vectors to see which is longest, as this avoids computing square roots
    a.squaredLength() = a.x * a.x + a.y * a.y;
  • float unit(): Returns a vector pointing on the same direction, but with a length of 1.
    a.unit() = a / a.length();
  • Vector2f turnLeft(): Returns the vector rotated 90 degrees left. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnRight)
    a.turnLeft = Vector2f(-a.y, a.x); 
  • Vector2f turnRight(): Returns the vector rotated 90 degrees right. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnLeft)
    a.turnRight = Vector2f(a.y, -a.x);
  • Vector2f rotate(float angle): Rotates the vector by the specified angle. This is an extremely useful operation, though it is rarely found in Vector classes. Equivalent to multiplying by the 2×2 rotation matrix.
    a.rotate(angle) =  Vector2f(a.x * cos(angle) – a.y * sin(angle), a.x * sin(angle) + a.y * cos(angle));
  • float angle(): Returns the angle that the vector points to.
    a.angle() = atan2(a.y, a.x);

Simple cases – warming up

Case #01 – Distance between two points

You probably know that this is done with the Pythagorean theorem, but the vectorial way is simpler. Given two vectors a and b:

float distance = (a-b).length();

Case #02 – Alignment

Sometimes, you want to align an image by its center. Sometimes, by its top-left corner. Or sometimes, by its top-center point. More generally, you can do alignment using a vector whose two components go from 0 to 1 (or even beyond, if you’d like), giving you full control of alignment.

// imgPos, imgSize and align are all Vector2f
Vector2f drawPosition = imgPos + imgSize * align

Case #03 – Parametric Line Equation

Two points define a line, but it can be tricky to do much with this definition. A better way to work with a line is its parametric equation: one point (“P0″) and a direction vector (“dir”).

Vector2f p0 = point1;
Vector2f dir = (point2 - point1).unit();

With this, you can, for example, get a point 10 units away by simply doing:

Vector2f p1 = p0 + dir * 10;

Case #04 – Midpoint and interpolation between points

Say you have vectors p0 and p1. The midpoint between them is simply (p0+p1)/2. More generally, the line segment defined by p0 and p1 can be generated by varying t between 0 and 1 in the following linear interpolation:

Vector2f p = (1-t) * p0 + t * p1;

At t = 0, you get p0; at t = 1, you get p1; at t = 0.5, you get the midpoint, etc.

Case #05 – Finding the normal of a line segment

You already know how to find the direction vector of a line segment (case #03). The normal vector is a 90 degree rotation of that, so just call turnLeft() or turnRight() on it!

Projections using the Dot Product

The dot product has the incredibly useful property of being able to compute the length of a vector’s projection along the axis of another. To do this, you need the vector that you’ll project (“a“) and a unit vector (so make sure that you call unit() on it first!) representing the direction (“dir“). The length is then simply a.dot(dir). For example, if you have a = (3, 4) and dir = (1, 0), then a.dot(dir) = 3, and you can tell that this is correct, because (1, 0) is the direction vector of the x axis. In fact, a.x is always equivalent to a.dot(Vector2f(1, 0)), and a.y is equivalent to a.dot(Vector2f(0, 1)).

Because the dot product between a and b is also defined as |a||b|cos(alpha) (where alpha is the angle between the two), the result will be 0 if the two vectors are perpendicular, positive if the angle between them is less than 90, and negative if greater. This can be used to tell if two vectors point in the same general direction.

If you multiply the result of that dot product by the direction vector itself, you get the vector projected along that axis – let’s call that “at” (t for tangent). If you now do a – at, you get the part of the vector that is perpendicular to the dir vector – let’s call that “an” (n for normal). at + an = a.

Case #06 – Determining direction closest to dir

Say that you have a list of directions represented as unit vectors, and you want to find which of them is the closest to dir. Simply find the largest dot product between dir and a vector in the list. Likewise, the smallest dot product will be the direction farthest away.

Case #07 – Determining if the angle between two vectors is less than alpha

Using the equation above, we know that the angle between two vectors a and b will be less than alpha if the dot product between their unit vectors is less than cosine of alpha.

bool isLessThanAlpha(Vector2f a, Vector2f b, float alpha) {
    return a.unit().dot(b.unit()) < cos(alpha);
}

Case #08 – Determining which side of a half-plane a point is on

Say that you have an arbitrary point in space, p0, and a direction (unit) vector, dir. Imagine that an infinite line goes by p0, perpendicular to dir, dividing the plane in two, the half-plane that dir points to, and the half-plane that it does not point to. How do I tell whether a point p is in the side pointed to by dir? Remember that dot product is positive when the angle between vectors is less than 90 degrees, so just project and check against that:

bool isInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    return (p - p0).dot(dir) >= 0;
}

Case #09 – Forcing a point to be inside a half-plane

Similar to the case above, but instead of just checking, we’ll grab the projection and, if less than 0, use it to move the object -projection along dir, so it’s on the edge of the half-plane.

Vector2f makeInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    float proj = (p - p0).dot(dir);
    if (proj >= 0) return p;
    else return p - proj * dir;
}

Case #10 – Checking/forcing a point inside a convex polygon

A convex polygon can be defined to be the intersection of several half-planes, one for each edge of the polygon. Their p0 is either vertex of the edge, and their dir is the edge’s inner-facing normal vector (e.g., if you wind clockwise, that’d be the turnRight() normal). A point is inside the polygon if and only if it’s inside all the half-planes. Likewise, you can force it to be inside the polygon (by moving to the closest edge) by applying the makeInsideHalfPlane algorithm with every half-plane. [ops, this actually only works if all angles are >= 90 degrees]

Case #11 – Reflecting a vector with a given normal

Pong-like game. Ball hits a sloped wall. You know the ball’s velocity vector and the wall’s normal vector (see case #05). How do you reflect it realistically? Simple! Just reflect the ball’s normal velocity, and preserve its tangential velocity.

Vector2f vel = getVel();
Vector2f dir = getWallNormal(); // Make sure this is a unit vector
Vector2f velN = dir * vel.dot(dir); // Normal component
Vector2f velT = vel - velN; // Tangential component
Vector2f reflectedVel = velT - velN;

For more realism, you can multiply velT and velN by constants representing friction and restitution, respectively.

Case #12 – Cancelling movement along an axis

Sometimes, you want to restrict movement in a given axis. The idea is the same as above: decompose in a normal and tangential speed, and just keep tangential speed. This can be useful, for example, if the character is following a rail.

Rotations

Case #13 – Rotating a point around a pivot

If used to represent a point in space, the rotate() method will rotate that point around the origin. That might be interesting, but is limiting. Rotating around an arbitrary pivot vector is simple and much more useful – simply subtract the pivot from it, as if translating so the origin IS the pivot, then rotate, then add the pivot back:

Vector2f rotateAroundPivot(Vector2f p, Vector2f pivot) {
    return (pos - pivot).rotate(angle) + pivot;
}

Case #14 – Determining which direction to turn towards

Say that you have a character that wants to rotate to face an enemy. He knows his direction, and the direction that he should be facing to be looking straight at the enemy. But should he turn left or right? The cross product provides a simple answer: curDir.cross(targetDir) will return positive if you should turn left, and negative if you should turn right (and 0 if you’re either facing it already, or 180 degrees from it).

Other Geometric Cases

Here are a few other useful cases that aren’t that heavily vector-based, but useful:

Case #15 – Isometric world to screen coordinates

Isometric game. You know where the (0, 0) of world is on the screen (let’s call that point origin and represent it with a vector), but how do you know where a given world (x, y) is on the screen? First, you need two vectors determining the coordinate base, a new x and y axes. For a typical isometric game, they can be bx = Vector2f(2, 1) and by = Vector2f(-2, 1) – They don’t necessarily have to be unit vectors. From now, it’s straightforward:

Vector2f p = getWorldPoint();
Vector2f screenPos = bx * p.x + by * p.y + origin;

Yes, it’s that simple.

Case #16 – Isometric screen to world coordinates

Same case, but now you want to know which tile the mouse is over. This is more complicated. Since we know that (x’, y’) = (x * bx.x + y * by.x, x * bx.y + y * by.y) + origin, we can first subtract origin, and then solve the linear equation. Using Cramer’s Rule, except that we’ll be a little clever and use our 2D cross-product (see definition at the beginning of the article) to simplify things:

Vector2f pos = getMousePos() - origin;
float demDet = bx.cross(by);
float xDet = pos.cross(by);
float yDet = bx.cross(pos);
Vector2f worldPos = Vector2f(xDet / demDet, yDet / demDet);

And now you don’t need to do that ugly find-rectangle-then-lookup-on-bitmap trick that I’ve seen done several times before.

334 ResponsesLeave one →

  1. Home enter GTA : CW GTA : tbogt GTA : TLAD GTA : IV GTA V RSS. Download/Загрузить. ЮЗЕРБАРЫ/USERBARS. Wallpapers/ОБОИ GTA V . GTA 5 скачать торрент GTA V .

  2. ЭЙ БРО, на чём играешь в GTA 5 или online? На прошлой неделе Rockstar решила поиграть в центробанк и объявила, что каждый игрок GTA . Первая Московская Банда в ГТА 5 . Костумная эмблема — не стыдно носить!

  3. Скачать IMG Tool 2.0 – Программы – Машины GTA san моды, прохождение. Программа сжимает файл gta 3. img больше чем на 50%. Вот Наченаем заходим на папку GTA _ San _ Andreas а потом models файл gta 3. 28 февраля 2014

  4. Не трудно догадаться, какие активные персонажи остаются после финальных титров . Тревор Филлипс GTA 5 покидает. Единственное существо в мире ГТА 5 Чоп – остается верным своему хозяину, не смотря ни на что. 5 апреля 2015

  5. Минимальные системные требования GTA 4 : • Операционная система : Windows XP SP3 или Windows Vista SP1 • Процессор: Intel Core 2 Duo 1.8 GHz / AMD Athlon X2 2. 4 GHz • RAM: 1, 5 Гб Предлагаем Вам сравнить с системными требованиями GTA 5 .

  6. Первый – взять технику на военной базе . Второй – приобрести аппарат на интернет-сайте за 2200000 $. Новое на сайте. Стрип клуб ГТА 5 03.04.2015. gta 5 где найти вертолет 02.04.2015. Карта прыжков в Grand Theft Auto V 01.04.2015. 3 апреля 2015

  7. Прыжки с парашютом в Саратове . Федерация парашютного спорта поможет воспарить над землей. А спортивная федерация парашютного спорта в Саратове научит этими крыльями управлять.

  8. Установка игры: 1.Распаковать архив RAR 2.Установить файл ехе 3.Запустить игру 4.Играть! Скачать GTA San Andreas – Super Cars GTA / Grand Theft Auto : San Andreas – Endless Summer (2005-2014/Rus/Mod). GTA SA Best Sunny Mod (PC/2010/RePack). 20 июля 2012

  9. По сообщениям российских розничных сетей, издательство "1С-Софтклаб" начало рассылать комплекты предварительного заказа GTA 5 , которые поступят в продажу на следующей неделе. Комплект предзаказа будет стоить 299 рублей. 14 января 2013

  10. Grand Theft Auto 5 , или сокращенно GTA 5 / ГТА 5 – игра в жанре экшн с открытым миром. Несколько позже, 18 ноября 2014 года , релиз GTA 5 состоялся на консолях Xbox One и PS 4 .

  11. Русификатор Grand Theft Auto IV и Grand Theft Auto : Episodes from Liberty City [Steam – . 3 апреля 2009 в 11:33 #. Desings Почему твой кряк не идет у меня.300 раз перезапустил игру а толку нету,сразу вырубает и все.

  12. кирпича на Grand Theft Auto IV – технические проблемы – Page 32 – GTA * Когда установил GTA 4 и попытался БЕЗ МОДОВ И ТАЧЕК)установлен только 4 патч и кряк от разора. . как исправить пьяный экран без прог. может что-нибудь закинуть

  13. мангал в виде Mercedes Gelandewagen (18 фото). # приколы #девушки Бесчисленное количество нарушений за 1, 5 минуты – видео #fun #girls # приколы #девушки Проявление доброты на дорогах России – видео #fun #girls # приколы #девушки

  14. GTA IV Games – Одиннадцатый титул в серии Grand Theft Auto игр. Нравится программа? Поделись с друзьями! Asphalt 5 HD FREE ( Android ) Невероятно популярные гонки возвращаются.

  15. Откуда ты такие цены берешь А, Люди GTA Complete Pack по 150р продают. нафиг кому нужны твои эти ограничение. @Omich, Цена реально завышена. Её сейчас можно купить за 50р. Всё из-за предзаказа GTA V.

  16. Скопировать trainer. asi и trainer.ini в папку с игрой, так же должен быть установлен asi loader и scripthook (есть в папке с TCS). 2. кряк для GTA IV – без музыки, без багов. (от GSC). 19 июня 2011

  17. [SFM – The Epic Run of Slenderman 01:19. СЛЕНДЕР Ð’ ГТА / ОБЗОР МОДА ( GTA San Andreas: Slender Man )09:20. Встретил Слендер Мэна01:20. Мифы Gta San Andreas "Мофман"06:16.

  18. Ð’ сети появился слух о том, что на новой портативной консоли PS Vita будет своя GTA 5. А точнее – GTA 5 Stories . Вполне логичное предположение, если учесть, что в свое время на PSP выходила Liberty City Stories .

  19. 14 февраля 2012 Персонажи GTA 5 . Скриншоты, Арты, Обои и различные картинки Grand Theft Auto 5 . … Новости GTA 5 на GTA Last News vk.com. Пиар-компания GTA 5 ( Epsilon Program).

  20. Программы Коды Карты Видео Прохождение. Системные требования Мультиплеер. Совместно с партнерами из ГТА 5 .РФ была осуществлена идея создания мощной российской банды GTA Online, которая объединяла бы в своем кругу преданных и

  21. Во время прохождения GTA 5 , миссий , которые связаны с акциями, отложить их на потом, чтобы когда у вас уже будет приличная сумма денег и вы сможете закупиться акциями. КОНЦОВКИ GTA 5 . Миссия 74 — Последний рывок.

  22. раскрыть эту ветвь (0). у него был корабль, а в гта 5 нету корабля, который бы смог унести его в океан ведь там можно плавать а остров обитаемый лишь один. А вот файлика GTA 5.exe не хватает. Можете открыть лаунчер, создастся эта папка C:\Users

  23. Keep it up bro and thanks for sharing useful information. I m Bookmarked this website for latest internet Stuff.

  24. гугл переводчик Сидоджи промт гта сан андреас охладите трахание песочница. Я сейчас вспоминаю детство, снова играя в GTA SA, и порой натыкаюсь на весьма гта сан андреас Игры перевод Cyanide and happiness Комиксы ГТА песочница.

  25. Уверен многие ждали выхода мода GTA San Andreas – Криминальная Россия и вот появившись она уже успела стать известной Ð’ игре все оружие заменено на русское. Также в игре теперь вся полиция стала русской, гта криминальная Россия все же.

  26. N- TORRENTS .RU » Игры для PC » Большие игры на PC » Скачать торрент GTA 4 / Grand Theft Auto IV : ModS ( 2012 /PC/Русский) | RePack от Strel0k56 [13.14 Гб – .

  27. Bmw(бмв) для gta san andreas , gta criminal russia. Многие задаются вопросом, какой торрент из раздачи гта сан – андреас токийский Почему когда я скачаю какойто скин или еще чтонибуть то иногда игра начинает очень глючит(появляются текстуры итд).

  28. Загрузить игру Grand Theft Auto Vice City ( GTA IV ) для Андроид на планшет Андроид бесплатно и без регистрации. Процессор: ArmV7 Версия ОС: Android 2.3+ Для игры необходим КЭШ.

  29. Все коды для GTA V ( GTA 5 )! Версия Xbox 360 и PS3! Коды сгруппированы на одной странице, на открытии приложения для быстрого доступа! – Material design like Android 5 Lollipop – Xbox 360, Xbox One , Playstation 3, Playstation 4, PC – New cars from all DLC !!!

  30. 17 июня 2013 Глава британского подразделения Sony Computer Entertainment Фергал Гара (Fergal Gara) заявил, что компания до последнего отказывалась от идеи платного мультиплеера на PS 4 , однако именно этот шаг позволил ей

  31. серии игр , скачать бесплатно, торрент файлы, новинки игры . Моды [9 – . Hulk Script — мод фантастического супергероя Халка , которого запустили в Либерти-Сити.

  32. TorrentRex.Ru » Игры » Экшн » GTA 4 / Grand Theft Auto IV : Complete Edition (2010) PC | RePack от R.G. Games. Папку переименовать. Из каждой папки удалить: readme.txt, Setup.exe, Setup-1a.bin- перекачать. 25.09. 2013 20:42 (Время Киевское).

  33. Моды на ГТА Сан Андреас : ENB моды, спидометры, моды MAIN.SCM . Установка : 1. Моды машин , CLEO скрипты с автоматической установкой в GTA San Andreas , GTA 5, GTA 4, GTA Vice City. Все наши

  34. 4 февраля 2015 Тут презентабельная обитель зла, на которую igru gta grand theft auto iv multiplayer экономить время за счет денег. только одна возможная. сражения. … Плюсы: неплохие гта 5 дети горы гта сан андреас где находится сражения.

  35. Как управлять вертолетом : Техника. О тонкостях управления вертолетом Robinson R44 рассказывает старший тренер вертолетного клуба «Аэро-союз» Сергей Друй.

  36. Название: GTA San Andreas – Super Cars Год выхода: 2011 Жанр: Action Разработчик: Rockstar Games Издатель: Rockstar Games Язык интерфейса: Русский Лекарство: Не требуется.

  37. Думаю многие уже сейчас готовы сделать предзаказ на gta 5 в steam но для России он не доступен,а в Украине игра стоит 49.99$. http://www.g2a.com/ grand – theft – auto -v-cd- key -preorder-r.. Купите тут, она тут 30 долларов стоит.

  38. GTA V Community GTA -V. Присоединиться. Обзор Объявления Обсуждения События Участники посмотреть все < >. шуруп 16 мар в 19:18. Сделал предзаказ .

  39. Вы решили купить эксклюзивный, платиновый, бриллиантовый, золотой, красивый мобильный VIP(Вип) номер оператора Украины: МТС, Киевстар , Диджус, Билайн У человека, который с Вами знакомится, читает рекламу с Вашим номером телефона

  40. «В Grand Theft Auto 5 создан самый большой, самый реалистичный и самый разнообразный открытый игровой мир. По последней информации GTA 5 появится в продаже для PS3 и Xbox 360 уже 17 сентября 2013 года.

  41. Миссия « Пролог » является самой первой в игре GTA 5 во время её прохождения . Золотая награда, прохождение на 100%. Чтобы получить золотую награду в миссии Вам придется пройти миссию до конца.

  42. с остальными гайдами по GTA 5, где подробно рассказывается о прохождении игры на 100%. Где найти все коллекционные места в ГТА 5? В GTA 5 есть более чем 180 GTA 5 Все части деталей подводной лодки. Карта для задания Абигейл.

  43. Обзор игры GTA 5 . Прохождение, секреты , баги, приколы в игре GTA 5 . GTA 5 Мифы тайны и секреты . НЛО и иноплонетяни . Gta V Myths.UFO. Октябрь 30th, 2014. 30 октября 2014

  44. весь сан андреас превратился в зомби апокалипсис ужас Никита Петров (4 мес. назад). Мод использованный при снятии видео " Zombie Andreas "?.

  45. Скачать gta 4 intro бесплатно в mp3 просто – нажмите кнопку скачать , и слушать онлайн песню gta 4 intro. и другие песни популярного музыканта Michael Hunter, который не устает удивлять своих поклонников лучшими мелодиями, например Soviet

  46. четверка однозначно длинней 1 сюжет в gta sa намного интересней чем в четверке (играл в русские версии ) sa намного легче чем четверка. правду говоря гта 4 лучше чем сан андреас но лучше из лучшых и лучшых это игра Gta vice city.

  47. Resident Evil Revelations 2 (2015) (RUS/ENG) (PC). Скачать бесплатно файлы для GTA 5 / Grand Theft Auto V (2013) (RUS) ( XBOX 360 ): карты, моды, патчи, дополнения, русификатор, nodvd, трейлеры и видео ролики, полная русская версия, бесплатные

  48. Машины для GTA sa , транспорт для GTA sa ,скачать игру GTA sa , бесплатно GTA sa GTA Sa crazy trainer +151. [ · Скачать удаленно () – . 19.06.2011, 16:50.

  49. Морское чудовище в Assassin's Creed 3 – Продолжительность: 4 :40 a1zberg 4 551 просмотр. Мифы GTA 5 – (Выпуск 19 "Лох-несское чудовище ") – Продолжительность: 15:29 LaytCoolShow 211 162 просмотра.

  50. Где скачать save для gta san andreas , и куда их копировать потом \ MAC OS 1 ставка. ••• Я все-таки сдался и сделал предзаказ GTA 5. Я слабак? Тифус Просветленный (29651), закрыт 1 день назад. 3 апреля 2015

Leave a Reply to Zedaa

*