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. Thanks for making this! I’m doing some 2D vector collision detection at the moment and this helped.

  2. Very useful! Thanks.

  3. very sweet! Love all your posts.

    Keep it coming, lets have one with quaternions and camera control – how to do first and third person – next?

    Captcha was 73LD, and I thought we were only on the 24th LD?

  4. Rons

     /  2012-09-03

    Omg, I wish I had read this article ten years ago. My code is full of the things that vectors would have solved. It’s like seeing the light. Almost made me cry:) Thanks!

  5. Lord Voldemoo

     /  2012-09-04

    Really well done! I had (am still having, actually) problems visualizing Case #10. An illustration here would be really helpful. I guess I also don’t yet know the “why” for this operation.

  6. Well done. It takes me back many a year. When I use to do equations for aircraft simulators

  7. Cara seus posts são ótimos, achei que o site estivesse abandonado. Compartilhe conosco mais conhecimentos sobre a areá de desenvolvimento de jogos. Obrigado!

  8. Keep it coming Rodrigo.

    The articles are very well written and useful. I’m really looking forward to more articles like this.Keep it coming Rodrigo.

    The articles are very well written and useful. I’m really looking forward to more articles like this.

  9. evetro

     /  2012-09-07

    “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.”
    This is not true.

  10. amz

     /  2012-09-07

    evetro, you’re right. This only works for polygons whose internal angles are all >= 90 degrees. Will update post.

  11. If you enjoy this series (I do) – you might be interested in raytracing as well – I wrote a small series explaining the math behind that and implementing it in F# some time ago.
    You can find it here: http://gettingsharper.de/tag/raytracing/

  12. Truck

     /  2013-04-04

    This whole series has been very, very helpful. Thank you so much for your efforts. I hope that you shall continue to share your hard won knowledge.

  13. Thanks a lot for sharing this with all folks you actually
    recognise what you’re talking about! Bookmarked. Kindly also consult with my web site =). We will have a hyperlink exchange agreement among us

  14. Meganopteryx

     /  2013-08-09

    This is an EXCELLENT reference. Thanks for providing! Question on Case #10, isn’t a convex polygon by definition a polygon with all angles >= 90 degrees?

  15. Hi to all,the contents present at this web site are
    really remarkable for peopple knowledge, well, keep up the nice
    work fellows.

  16. mnemy

     /  2014-02-25

    I’ve been reading up on Vector math from a couple other sources, and wasn’t quite understanding just how I can use dot/cross products, but I finally think I get it thanks to these very well written explanations and examples. I think some diagrams like you put in your earlier posts would make some of these more complex cases easier to visualize. Thanks for taking the time to share this valuable knowledge!

  17. I see a lot of interesting posts on your page. You have to spend a lot of time writing, i know how to
    save you a lot of work, there is a tool that creates high quality, google friendly posts in couple of seconds, just search in google – k2 unlimited content

  18. I read a lot of interesting articles here. Probably you spend a lot of time writing,
    i know how to save you a lot of work, there is an online tool that creates readable, google friendly articles in seconds, just type in google
    – laranitas free content

  19. Thank for the Awesome information in the post

  20. eval(ez_write_tag([[468,60],’brighthubpm_com-banner-1′]));.
    For instance, the New York Times sorts by category (fiction, nonfiction,
    children. So, literary works may not tell us true stories but they are stories based on truth.

  21. Kanika

     /  2016-02-10

    thanks for sharing this article with us great writing way. Math for game programmers please you can explain me in simple way what it is exactly about

  22. Latest Govt Jobs

     /  2016-02-10

    Thanks admin to share this useful article with us keep it up and write some more like this one.

  23. this is awesome article thanks for sharing with us

  24. Nice and informative post. thanks to share with us. Happy to read.

  25. this is nice information in this post.

  26. I am very sympathetic to your viewpoint. It is very deep and meaningful. I think you should write many more articles to the reader to understand. I would recommend it to everyone.

  27. Great. This article is excellent. I have read many articles with this topic, but I have not liked. I think I have the same opinion with you.

  28. let’s play abcya games

  29. Say, you got a nice forum topic.Thanks Again. Keep writing. Stallard

  30. click to play wingsio

  31. click to play slither io

  32. let’s click happy wheels to play for free

  33. let’s play wings.io games

  34. let’s play abcya games

  35. Название: Чиж & Со ( CHIJ & Co) Исполнитель: Чиж & Со Год: 1993-1999 Жанр: Русский рок, блюз-рок, фолк-рок Страна: СССР. Продолжительность: 07:41:00 Формат/Кодек: MPEG 1 Audio, Layer 3 ( MP3 ) Битрейт аудио: 192 kbps.

  36. Лучшие трюки на BMX в GTA 5 . Макс Курчавов. 4 просмотра • 8 месяцев назад. Павел Воля – про контакт (НОВЫЙ ПРИКОЛ ИЗ КАМЕДИ КЛАБ 2013) приколы юмор ржач угар лучшее жесть интересное просветление.

  37. ОХОТА на ЛОСЯ и КАБАНА ЗАГОНОМ. СМОЛЕНСКАЯ ОБЛАСТЬ. Объект охоты : КАБАН с вышки. Сезон охоты : с 1 июня по 28 февраля. Продолжительность охоты : 3- 5 дней.

  38. Оружие в Grand Theft Auto : San Andreas. Police (Полиция). Скачать игру ГТА Сан Андреас. • GTA San-Andreas » Все о девушках в GTA : San Andreas » Denise Robinson (Дениз Робинсон) » На танцах с Дениз.

  39. Обменяю ноутбук на PS 4 + GTA 5 . Цель: Обмен. Номер телефона: 79500975010. Обменяю ноутбук Acer Aspire E1-572G-74506G50Mnkk (черный) на PS 4 + GTA 5 Ноутбук в хорошем состоянии,ничего не ломалось,все документы есть,гарантия ещё действует.

  40. специальное и коллекционное издания консольных версий Grand Theft Auto V . В Singularity 13.03.2015 16:21:1310Mortal Kombat X на Xbox 360 и PS3 задержится до лета ограбления 16.12.201410 ИГРЫ Трейлер к выходу GTA 5 на PlayStation 4 и Xbox One.

  41. Скажите пойдёт ли у меня гта 5 на пк и что нужно в первую очередь заменить. Минимальные системные требования для GTA 5 уже опубликованы. Ваш ноутбук подходит.

  42. Как же задрали школьники в гта 5 Нормально не дают тагсу поснимать видео !(я про миху) Миха,я надеюсь что У меня есть гта 5 на pc классная игра жесть скачивайте не пожелейте классная игрушка но есть одно но я скачиваю и оно скачивается 5 дней но

  43. У нас можно бесплатно скачать игры торрент, фильмы торрент, Музыку торрент, новинки и т.д. У нас Вы найдете, то что Вам нужно, любой фильм, сериал, музыку. Заходите на TorrentBest.ru! Скачать GTA Criminal Russia / Криминальная Россия 2 июля 2013

  44. CLEO скрипты для GTA San Andreas – Оживление военной базы в доках с автоматической установкой скачать бесплатно. люди где . GTA Vice City GTA San Andreas GTA IV Для всех одинаково Мне всё равно.

  45. На нашем GTA портале, вы сможете скачать бесплатно, Стандартный gta _sa. exe , и без регистрации как и все остальные файлы нашего сайта. Стандартный gta _sa. exe — пиратский файл для запуска игры, взял из своей папки GTA .

  46. Описание, история ГТА и ГТА 4 Ответов: 2. Главная » Файлы » Машины для GTA 4 . Всего материалов в каталоге: Показано материалов: Bobcat on Custom 24" Rims .

  47. Серия Grand Theft Auto известна своим скандальным нравом и огромным простором для творчества. Однако в GTA 4 абсолютной вседозволенности нет – на этот раз игра соблюдает правила реальной жизни. *Репак сделан с английской лицензии .

  48. Коды на GTA 5 ГТА 5 для PC, Xbox 360, One, PS3, PS 4 / GTA . Поделки из носков кот и лошадь. gta 4 код на бессмертие для xbox 360. Загадки с ответами 147 уровень.

  49. GTA IV (Full OST ). Год выхода: 2008. Жанр: Soundtrack . Общая продолжительность: 20 мин 1) Michael Hunter – Grand Theft Auto IV Game Intro (1:04) 2) Michael Hunter

  1. Math for Game Programmers 04 – Operations on vectors | Higher-Order Fun
  2. Link: Higher-Order Fun | Keith M. Programming
  3. Matemática para programadores de Jogos: Vetores e Ângulos |

Leave a Reply to EarnestKn

*