<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Higher-Order Fun &#187; math</title>
	<atom:link href="http://higherorderfun.com/blog/tag/math-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://higherorderfun.com/blog</link>
	<description>Game Design &#38; Game Programming</description>
	<lastBuildDate>Sun, 31 Aug 2014 00:02:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.39</generator>
	<item>
		<title>Math for Game Programmers 05 &#8211; Vector Cheat Sheet</title>
		<link>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/</link>
		<comments>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/#comments</comments>
		<pubDate>Sun, 03 Jun 2012 17:23:53 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[articles]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=123</guid>
		<description><![CDATA[This is the long due fifth article in this series. If you aren&#8217;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 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This is the long due fifth article in this series. If you aren&#8217;t comfortable with vectors, you might want to take a look at the first four articles in this series before: <a href="http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-01-introduction/">Introduction</a>, <a href="http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-02-vectors-101/">Vectors 101</a>, <a href="http://higherorderfun.com/blog/2009/06/13/math-for-game-programmers-03-geometrical-representation-of-vectors/">Geometrical Representation of Vectors</a>, <a href="http://higherorderfun.com/blog/2010/02/23/math-for-game-programmers-04-operations-on-vectors/">Operations on Vectors</a>.</p>
<p>This cheat sheet will list several common geometrical problems found in games, and how to solve them with vector math.</p>
<p><span id="more-123"></span></p>
<h2>Complete list of basic vector operations</h2>
<p>But first, a little review.</p>
<p>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 &#8220;z&#8221; axis. Any case that only applies to 2D or 3D will be pointed out.</p>
<p>Strictly speaking, a point is not a vector &#8211; 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.</p>
<p>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 &#8211; 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 &#8220;VectorUtils&#8221; class. The examples below are usually for 2D vectors &#8211; but 3D is usually simply a matter of adding the z coordinate following the pattern of x and y.</p>
<ul>
<li><strong><em>Vector2f operator+(Vector2f vec): </em></strong>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.)<br />
<em>a + b = Vector2f(a.x + b.x, a.y + b.y);</em></li>
<li><em><strong><em>Vector2f operator-(Vector2f vec):Â </em></strong></em>Returns the difference between the two vectors.<em><br />
<em>a &#8211; b = Vector2f(a.x &#8211; b.x, a.y &#8211; b.y);</em></em></li>
<li><em><em><strong><em>Vector2f operator*(Vector2f vec):Â </em></strong></em></em>Returns the component-wise multiplication of the vectors.<em><em><br />
<em>a * b = Vector2f(a.x * b.x, a.y * b.y);</em></em></em></li>
<li><em><em><em><strong><em>Vector2f operator/(Vector2f vec):Â </em></strong></em></em>Returns the component-wise division of the vectors.<em><em><em><em><br />
<em>a / b = Vector2f(a.x / b.x, a.y / b.y);</em></em></em></em></em></em></li>
<li><strong><em>Vector2f operator*(float scalar)</em></strong>: Returns the vector with all components multiplied by the scalar parameter.<br />
<em>a * s = Vector2f(a.x * s, a.y * s);<br />
s * a = <em>Vector2f(a.x * s, a.y * s);</em></em></li>
<li><em><strong><em>Vector2f operator/(float scalar)</em></strong>: </em>Returns the vector with all components divided by the scalar parameter.<em><br />
<em>a / s = Vector2f(a.x / s, a.y / s);</em></em></li>
<li><strong><em>float dot(Vector2f vec)</em></strong>: Returns the dot product between the two vectors.<br />
<em>a.dot(b) = a.x * b.x + a.y * b.y;</em></li>
<li><strong><em>float cross(Vector2f vec)</em></strong>: (2D case) Returns the z component of the cross product of the two vectors augmented to 3D.<br />
<em>a.cross(b) = a.x * b.y &#8211; a.y * b.x;</em></li>
<li><strong><em>Vector3f cross(Vector3f vec)</em></strong>: (3D case) Returns the cross product of the two vectors.<br />
<em>a.cross(b) = Vector3f(a.y * b.z &#8211; a.z * b.y, a.z*b.x &#8211; a.x*b.z, a.x*b.y &#8211; a.y*b.x);</em></li>
<li><strong><em>float length()</em></strong>: Returns the length of the vector.<br />
<em>a.length() = sqrt(a.x * a.x + a.y * a.y);</em></li>
<li><em><strong>float squaredLength()</strong>: </em>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<br />
<em>a.squaredLength() = a.x * a.x + a.y * a.y;</em></li>
<li><strong><em>float unit()</em></strong>: Returns a vector pointing on the same direction, but with a length of 1.<br />
<em>a.unit() = a / a.length();</em></li>
<li><em><strong>Vector2f turnLeft()</strong>: </em>Returns the vector rotated 90 degrees left. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnRight)<br />
<em>a.turnLeft = Vector2f(-a.y, a.x);Â </em></li>
<li><em><em><strong>Vector2f turnRight()</strong>:Â </em></em>Returns the vector rotated 90 degrees right. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnLeft)<em><br />
<em>a.turnRight = Vector2f(a.y, -a.x);</em></em></li>
<li><strong>Vector2f rotate(float angle)</strong>: 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&#215;2 rotation matrix.<br />
<em>a.rotate(angle) = Â Vector2f(a.x * cos(angle) &#8211; a.y * sin(angle), a.x * sin(angle) + a.y * cos(angle));</em></li>
<li><strong><em>float angle():Â </em></strong>ReturnsÂ the angle that the vector points to.<br />
<em>a.angle() = atan2(a.y, a.x);</em></li>
</ul>
<h2>Simple cases &#8211; warming up</h2>
<h3>Case #01 &#8211; Distance between two points</h3>
<p>You probably know that this is done with the Pythagorean theorem, but the vectorial way is simpler. Given two vectors <em>a</em> and <em>b</em>:</p>
<pre class="brush: cpp; title: ; notranslate">float distance = (a-b).length();</pre>
<h3>Case #02 &#8211; Alignment</h3>
<p>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&#8217;d like), giving you full control of alignment.</p>
<pre class="brush: cpp; title: ; notranslate">// imgPos, imgSize and align are all Vector2f
Vector2f drawPosition = imgPos + imgSize * align</pre>
<h3>Case #03 &#8211; Parametric Line Equation</h3>
<p>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 (&#8220;<em>P0&#8243;</em>) and a direction vector (&#8220;<em>dir&#8221;</em>).</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p0 = point1;
Vector2f dir = (point2 - point1).unit();</pre>
<p>With this, you can, for example, get a point 10 units away by simply doing:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p1 = p0 + dir * 10;</pre>
<h3>Case #04 &#8211; Midpoint and interpolation between points</h3>
<p>Say you have vectors <em>p0</em> and <em>p1</em>. The midpoint between them is simply <em>(p0+p1)/2</em>. More generally, the line segment defined by <em>p0</em> and <em>p1</em>Â can be generated by varying <em>t</em> between 0 and 1 in the following linear interpolation:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p = (1-t) * p0 + t * p1;</pre>
<p>At <em>t = 0</em>, you get <em>p0; </em>at <em>t = 1</em>, you get <em>p1</em>; at <em>t = 0.5</em>, you get the midpoint, etc.</p>
<h3>Case #05 &#8211; Finding the normal of a line segment</h3>
<p>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 <em>turnLeft()</em> or <em>turnRight()</em> on it!</p>
<h2>Projections using the Dot Product</h2>
<p>The dot product has the incredibly useful property of being able to compute the length of a vector&#8217;s projection along the axis of another. To do this, you need the vector that you&#8217;ll project (&#8220;<em>a</em>&#8220;) and a unit vector (so make sure that you call <em>unit()</em> on it first!) representing the direction (&#8220;<em>dir</em>&#8220;). The length is then simply <em>a.dot(dir)</em>. For example, if you have <em>a = (3, 4)</em> and <em>dir = (1, 0)</em>, thenÂ <em>a.dot(dir) = 3</em>, and you can tell that this is correct, because (1, 0) is the direction vector of the x axis. In fact, <em>a.x</em> is always equivalent to <em>a.dot(Vector2f(1, 0))</em>, and <em>a.y</em> is equivalent to <em>a.dot(Vector2f(0, 1))</em>.</p>
<p>Because the dot product between <em>a</em>Â and <em>b</em>Â is also defined as <em>|a||b|cos(alpha)</em> (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.</p>
<p>If you multiply the result of that dot product by the direction vector itself, you get the vector projected along that axis &#8211; let&#8217;s call that &#8220;<em>at</em>&#8221; (t for tangent). If you now do <em>a &#8211; at</em>, you get the part of the vector that is perpendicular to the <em>dir</em> vector &#8211; let&#8217;s call that &#8220;<em>an</em>&#8221; (n for normal). <em>at + an = a</em>.</p>
<h3>Case #06 &#8211; Determining direction closest to dir</h3>
<p>Say that you have a list of directions represented as unit vectors, and you want to find which of them is the closest to <em>dir</em>. Simply find the largest dot product between <em>dir</em> and a vector in the list. Likewise, the smallest dot product will be the direction farthest away.</p>
<h3>Case #07 &#8211; Determining if the angle between two vectors is less than alpha</h3>
<p>Using the equation above, we know that the angle between two vectors <em>a </em>and<em> b </em>will be less than alpha if the dot product between their unit vectors is less than cosine of alpha.</p>
<pre class="brush: cpp; title: ; notranslate">bool isLessThanAlpha(Vector2f a, Vector2f b, float alpha) {
    return a.unit().dot(b.unit()) &lt; cos(alpha);
}</pre>
<h3>Case #08 &#8211; Determining which side of a half-plane a point is on</h3>
<p>Say that you have an arbitrary point in space, <em>p0</em>, and a direction (unit) vector, <em>dir</em>. Imagine that an infinite line goes by <em>p0</em>, perpendicular to <em>dir</em>, dividing the plane in two, the half-plane that <em>dir</em>Â points to, and the half-plane that it does not point to. How do I tell whether a point <em>p</em> is in the side pointed to by <em>dir</em>? Remember that dot product is positive when the angle between vectors is less than 90 degrees, so just project and check against that:</p>
<pre class="brush: cpp; title: ; notranslate">bool isInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    return (p - p0).dot(dir) &gt;= 0;
}</pre>
<h3>Case #09 &#8211; Forcing a point to be inside a half-plane</h3>
<p>Similar to the case above, but instead of just checking, we&#8217;ll grab the projection and, if less than 0, use it to move the object -projection along dir, so it&#8217;s on the edge of the half-plane.</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f makeInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    float proj = (p - p0).dot(dir);
    if (proj &gt;= 0)Â return p;
    else return p - proj * dir;
}</pre>
<h3><span style="color: #000000;">Case #10 &#8211; Checking<del>/forcing</del> a point inside a convex polygon</span></h3>
<p><span style="color: #000000;">A convex polygon can be defined to be the intersection of several half-planes, one for each edge of the polygon. Their <em>p0</em> is either vertex of the edge, and their <em>dir</em> is the edge&#8217;s inner-facing normal vector (e.g., if you wind clockwise, that&#8217;d be the <em>turnRight()</em> normal). A point is inside the polygon if and only if it&#8217;s inside all the half-planes. <del>Likewise, you can force it to be inside the polygon (by moving to the closest edge) by applying the <em>makeInsideHalfPlane</em> algorithm with every half-plane.</del>Â [ops, this actually only works if all angles are &gt;= 90 degrees]</span></p>
<h3>Case #11 &#8211; Reflecting a vector with a given normal</h3>
<p>Pong-like game. Ball hits a sloped wall. You know the ball&#8217;s velocity vector and the wall&#8217;s normal vector (see case #05). How do you reflect it realistically? Simple! Just reflect the ball&#8217;s normal velocity, and preserve its tangential velocity.</p>
<pre class="brush: cpp; title: ; notranslate">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;</pre>
<p>For more realism, you can multiply velT and velN by constants representing friction and restitution, respectively.</p>
<h3>Case #12 &#8211; Cancelling movement along an axis</h3>
<p>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.</p>
<h2>Rotations</h2>
<h3>Case #13 &#8211; Rotating a point around a pivot</h3>
<p>If used to represent a point in space, the <em>rotate()</em> method will rotate that point around the origin. That might be interesting, but is limiting. Rotating around an arbitrary <em>pivot</em> vector is simple and much more useful &#8211; simply subtract the <em>pivot</em> from it, as if translating so the origin IS the <em>pivot</em>, then rotate, then add the <em>pivot</em> back:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f rotateAroundPivot(Vector2f p, Vector2f pivot) {
    return (pos - pivot).rotate(angle) + pivot;
}</pre>
<h3>Case #14 &#8211; Determining which direction to turn towards</h3>
<p>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 <em>cross</em> product provides a simple answer: <em>curDir.cross(targetDir)</em> will return positive if you should turn left, and negative if you should turn right (and 0 if you&#8217;re either facing it already, or 180 degrees from it).</p>
<h2>Other Geometric Cases</h2>
<p>Here are a few other useful cases that aren&#8217;t that heavily vector-based, but useful:</p>
<h3>Case #15 &#8211; Isometric world to screen coordinates</h3>
<p>Isometric game. You know where the (0, 0) of world is on the screen (let&#8217;s call that point <em>origin</em> 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 <em>bx = Vector2f(2, 1)</em>Â and <em>by = Vector2f(-2, 1)Â </em>&#8211; They don&#8217;t necessarily have to be unit vectors. From now, it&#8217;s straightforward:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p = getWorldPoint();
Vector2f screenPos = bx * p.x + by * p.y + origin;</pre>
<p>Yes, it&#8217;s that simple.</p>
<h3>Case #16 &#8211; Isometric screen to world coordinates</h3>
<p>Same case, but now you want to know which tile the mouse is over. This is more complicated. Since we know that <em>(x&#8217;, y&#8217;) = (x * bx.x + y * by.x, x * bx.y + y * by.y) + origin</em>, we can first subtract origin, and then solve the linear equation. Using <a href="http://en.wikipedia.org/wiki/Cramer%27s_rule">Cramer&#8217;s Rule</a>,Â except that we&#8217;ll be a little clever and use our 2D cross-product (see definition at the beginning of the article) to simplify things:</p>
<pre class="brush: cpp; title: ; notranslate">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);</pre>
<p>And now you don&#8217;t need to do that ugly find-rectangle-then-lookup-on-bitmap trick that I&#8217;ve seen done several times before.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>335</slash:comments>
		</item>
		<item>
		<title>Math for Game Programmers 04 &#8211; Operations on vectors</title>
		<link>http://higherorderfun.com/blog/2010/02/23/math-for-game-programmers-04-operations-on-vectors/</link>
		<comments>http://higherorderfun.com/blog/2010/02/23/math-for-game-programmers-04-operations-on-vectors/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 03:03:26 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[math]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vectors]]></category>

		<guid isPermaLink="false">http://higherorderfun.wordpress.com/?p=36</guid>
		<description><![CDATA[Last time, we introduced vectors, and hopefully that introduction alone would be compelling reason to use vectors where it makes sense to. This time, we&#8217;ll discuss common operations associated with vectors, and their many uses. All of these operations are commonly found in vector operation libraries. Length Like we&#8217;ve discussed on the previous post, the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Last time, we introduced vectors, and hopefully that introduction alone would be compelling reason to use vectors where it makes sense to. This time, we&#8217;ll discuss common operations associated with vectors, and their many uses. All of these operations are commonly found in vector operation libraries.</p>
<p><strong>Length</strong></p>
<p>Like we&#8217;ve discussed on the previous post, the length (or magnitude) of a vector is the square root of the sum of the squares of its components. So, if you have a 3D vector, its length is sqrt(xÂ²+yÂ²+zÂ²). It is often represented by writing the vector inside ||s, that is, the length of vector v is said to be |v|.</p>
<p>For example, if we have the vector (4,2,4), we have:</p>
<p>length((4,2,4)) = |(4,2,4)| = sqrt(4Â²+2Â²+4Â²) = sqrt(36) = 6</p>
<p><em>Application example</em>: If you have two points, you can find the vector between them and take its length to find the distance between the points.</p>
<p><strong>Multiplication by scalar</strong></p>
<p>You can multiply a vector by a scalar number (that is, a real number), which results in multiplying each component of the vector by that number. For example:</p>
<p>(0,-2,5) * 2 = (0,-4,10)</p>
<p>When you multiply a vector by a scalar, its direction is unchanged, but its length is multiplied by the scalar &#8211; for that reason, this operation is also called &#8220;scaling&#8221; the vector.</p>
<p><em>Application </em><em>example</em>: If you have an object moving with a vector representing its speed, you can adjust the speed without adjusting the direction by scaling the vector.</p>
<p><strong>Normalization</strong></p>
<p>By combining the two previous operations, we can &#8220;normalize&#8221; a vector. A vector is said to be normalized when its length is equal to 1. Since we can multiply any vector (except for (0,0,0)) by a scalar and therefore change its length to anything we want, we can normalize any vector by multiplying it by the inverse of its length.</p>
<p>In other words:</p>
<p>n = v * (1/|v|)</p>
<p>For convenience, many classes implementing vectors will define a &#8220;division by scalar&#8221; operator, so you could often just do this:</p>
<p>n = v/|v|</p>
<p><em>Application </em><em>example</em>: If you want a vector that represents a direction without a length, you usually want to use normalized vectors. It turns out, this is extremely common, and you will encounter normalized vectors very often.</p>
<p><strong>Dot Product</strong></p>
<p>Possibly the single most interesting operation on vectors, the dot product is very simple and versatile. It takes two vectors and returns a scalar number as the result, according to the following formula:</p>
<p>(a,b,c) . (d,e,f) = a*d + b*e + c*f</p>
<p>So, for example:</p>
<p>(2,-6,-10) . (1, 0, -1) = 2*1 + (-6)*0 + (-10)*(-1) = 2 + 10 = 12</p>
<p>It also has a different interpretation. Given two vectors v1 and v2, and let Î± be the angle between the two vectors, the dot product can be defined as:</p>
<p>v1 . v2 = |v1| * |v2| * cos(Î±)</p>
<p>This means that the angle between the two vectors can be determined like this:</p>
<p>Î± = arc cos( (v1 . v2) / (|v1| * |v2|) )</p>
<p>The formula above can easily be derived by isolating Î± on the previous equation. If the two vectors are normalized, then their lengths are one, and the dot product is simply the cosine of the angle between them.</p>
<p>One consequence of the cosine relationship is that the dot product can be used to determine the relative facing of two vectors. Let d be the dot product between two NORMALIZED vectors. Then:</p>
<p>v = 1: the two vectors face the exact same direction<br />
0 &lt; v &lt; 1: the two vectors face roughly the same direction<br />
v = 0: the two vectors are perpendicular<br />
-1 &lt; v &lt; 0: the two vectors face roughly opposite directions<br />
v = -1: the two vectors face exactly opposite directions</p>
<p>If you&#8217;re not interested in v=1 and v=-1 cases, then there is no need for the vectors to be normalized.</p>
<p><em>Applications</em>: finding angles between vectors, projecting vectors into specific axes, determining whether a vector is facing the right direction, neutralizing a vector along a given axis, etc</p>
<p><strong>Cross product</strong></p>
<p>Similar to the dot product, but instead of taking two vectors and producing a scalar, the vector product takes two vectors and produces a third vector. It is defined as follows:</p>
<p>(a,b,c) x (d,e,f) = (b*f-c*e, c*d-a*f, a*e-b*d)</p>
<p>Similar to the dot product, the cross product also has an angular relationship,</p>
<p>|v1 x v2| = |v1| * |v2| * sin(Î±)</p>
<p>It&#8217;s important to note that while the dot product is also defined for 2D vectors, the cross product is only defined for 3D vectors. However, since it has useful properties even for 2D, a pseudo vector product can be defined for 2D vectors as follows:</p>
<p>(a,b) x&#8217; (c,d) = a*d-b*c</p>
<p>This results in a scalar that is identical to what the &#8220;z&#8221; component of the result of extending the multiplication to 3D: (a,b,0) x (c,d,0) = (0,0,z)</p>
<p>A very important property of the cross product is that the cross between two vectors ALWAYS results in a vector that is perpendicular to the two original vectors (unless one of them was null). This makes the vector product extremely useful for calculating surface normal vectors &#8211; assuming that you can find three points on the surface, you can create the vectors v1 = (A-B) and v2 = (A-C), then n = v1 x v2, n&#8217; = n/|n|.</p>
<p>An interesting use for the cross product (in particular, the 2D version) is that it indicates which direction a vector must rotate in order to face the same direction as the other vector, by taking the shortest path. Simply take the cross product between &#8220;current facing&#8221; and &#8220;desired facing&#8221; vectors, and the sign of the number (i.e. whether it&#8217;s negative or positive) will tell you which way to turn.</p>
<p><em>Applications</em>: Finding normal vectors, finding turn directions, calculating torque, etc</p>
<p>These operations are some of the most basic things you can do with vectors. They will allow you to perform more complicated and interesting computations using vectors, so <em>make sure</em> that you understand them. We will use them very often in following lessons.</p>
<p>&nbsp;</p>
<p>The fifth article in this series is now available <a href="http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2010/02/23/math-for-game-programmers-04-operations-on-vectors/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Math for game programmers 03 &#8211; Geometrical representation of vectors</title>
		<link>http://higherorderfun.com/blog/2009/06/13/math-for-game-programmers-03-geometrical-representation-of-vectors/</link>
		<comments>http://higherorderfun.com/blog/2009/06/13/math-for-game-programmers-03-geometrical-representation-of-vectors/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 06:17:55 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[math]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vectors]]></category>

		<guid isPermaLink="false">http://higherorderfun.wordpress.com/?p=38</guid>
		<description><![CDATA[In the previous post, we introduced vectors, and showed some very elementary uses for them. We presented them as a simple and convenient way to pack a number (3, in our case) of scalar values into a single object. Now, we&#8217;ll consider their geometrical representation, which will help you grasp them more intuitively. For simplification&#8217;s [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In the previous post, we introduced vectors, and showed some very elementary uses for them. We presented them as a simple and convenient way to pack a number (3, in our case) of scalar values into a single object. Now, we&#8217;ll consider their geometrical representation, which will help you grasp them more intuitively. For simplification&#8217;s sake, we&#8217;ll use two-dimensional vectors for all our examples, but the same extends to 3D vectors.</p>
<p><strong>Points</strong></p>
<p>First, consider two points, A and B. A is located at (1, 2), and B is located at (4, 3) (If you are unfamiliar with the cartesian plane, points are represented as coordinate pairs in the form (x,y), so (1, 2) means that A is at x=1 and y=2), as shown in the following picture:</p>
<p><img class="aligncenter size-full wp-image-39" title="vectors_fig1" src="http://higherorderfun.com/blog/wp-content/uploads/2009/06/vectors_fig1.png" alt="vectors_fig1" width="450" height="330" />As we&#8217;ve mentioned in the previous post, positions in space can be represented as vectors. So we would have a vector A and a vector B, each representing one of the points in the figure. But points are not the SAME as vectors! A vector should always be thought of as a &#8220;delta&#8221;, it&#8217;s merely an increment. Without a reference, it&#8217;s meaningless as a position. For points, we adopt the point (0,0) as our <em>origin</em> (represented by the letter O), so all points can be represented as a vector from the origin. Drawing our vectors as arrows, we get this:</p>
<p><img class="aligncenter size-full wp-image-40" title="vectors_fig2" src="http://higherorderfun.com/blog/wp-content/uploads/2009/06/vectors_fig2.png" alt="vectors_fig2" width="450" height="330" />Consider it for a moment. If we have O=(0,0), and we add a vector A=(1,2) to it, you&#8217;ll get the point (0+1, 0+2) = (1,2), which is exactly our original point A. However, vector A by itself is merely an increment of 1 in x and an increment of 2 in y&#8230; As such, we could also represent it as:</p>
<p><img class="aligncenter size-full wp-image-42" title="vectors_fig4" src="http://higherorderfun.com/blog/wp-content/uploads/2009/06/vectors_fig4.png" alt="vectors_fig4" width="450" height="330" />This might all sound confusing, but don&#8217;t worry, it&#8217;ll eventually &#8220;click&#8221; into place! If you don&#8217;t fully understand the concept now, don&#8217;t worry about it.</p>
<p><strong>Addition and Subtraction</strong></p>
<p>What if you took vector B and subtracted A from it? From our previous lesson, we know that B &#8211; A is simply (B.x &#8211; A.x, B.y &#8211; A.y), so, given that B = (4, 3) and A = (1, 2), B-A = (3, 1). Let&#8217;s call that vector &#8220;C&#8221;. If we do A + C, we should naturally get B back: (1, 2) + (3, 1) = (4, 3). If you remember that we said that vectors are merely offsets, then this means that we can represent C as the vector that takes &#8220;A&#8221; and turns it into &#8220;B&#8221;, as in the following picture:</p>
<p><img class="aligncenter size-full wp-image-41" title="vectors_fig3" src="http://higherorderfun.com/blog/wp-content/uploads/2009/06/vectors_fig3.png" alt="vectors_fig3" width="450" height="330" />If you look to the axes, you&#8217;ll see that vector C (the orange vector) spans x from 1 to 4, meaning that its x component is 3 (4-1), and y from 2 to 3, meaning that its y component is 1 (3-2).</p>
<p><strong>Length and Distances</strong></p>
<p>The geometrical representation of vectors leads to a very intuitive way to understand one of their most important operations, length. The length of a vector (or magnitude) is simply its geometrical length! Take vector B, for example. It has a x component of 4, and a y component of 3. How can we get its length? The <a href="http://en.wikipedia.org/wiki/Pythagorean_theorem">pythagorean theorem</a> solves that for us: we simply take the square root of the sum of its squared components. For a 2D vector, length = sqrt(xÂ²+yÂ²). For a 3D vector, length = sqrt(xÂ²+yÂ²+zÂ²), and so forth.</p>
<p>For example, the length of vector B is sqrt(3Â²+4Â²) = sqrt(25) = 5.</p>
<p>One immediate use for the length operation is to find distances. Say that you want to find the distance between points A and B. You subtract one from the other (order doesn&#8217;t matter), and take its length. In C++, that would look as simple as:</p>
<pre class="brush: cpp; title: ; notranslate">

float distance = (a-b).length();

</pre>
<p>The reason why the order of the subtraction doesn&#8217;t matter is that (A-B) results in the opposite vector of (B-A), that is, a vector with the same length, but opposite direction. A-B results in (-3,-1), and B-A in (3,1). Both have a length of sqrt(10).</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2009/06/13/math-for-game-programmers-03-geometrical-representation-of-vectors/feed/</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>Math for game programmers 02 &#8211; Vectors 101</title>
		<link>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-02-vectors-101/</link>
		<comments>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-02-vectors-101/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 20:56:17 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[math]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[vectors]]></category>

		<guid isPermaLink="false">http://higherorderfun.wordpress.com/?p=18</guid>
		<description><![CDATA[If you don&#8217;t already use vectors (and I mean vectors in the MATHEMATICAL sense, not in the &#8220;dynamic array&#8221; sense that languages like C++ or Java use), this is probably going to be the single most useful piece of math you can learn for writing games. It&#8217;s easy, efficient, and makes your code much shorter. [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you don&#8217;t already use vectors (and I mean vectors in the MATHEMATICAL sense, not in the &#8220;dynamic array&#8221; sense that languages like C++ or Java use), this is probably going to be the single most useful piece of math you can learn for writing games. It&#8217;s easy, efficient, and makes your code much shorter. In fact, provided that you&#8217;re using a language that supports definition of operators for user-defined types (like, say, C++ or Haskell), using vectors is going to be extremely intuitive and simple.</p>
<p><strong>Motivation: The Ugly Code<br />
</strong></p>
<p>Consider that you want to simulate some simple physics, such as an object accelerating in 3D space. We&#8217;re going to use the formulas Î”s = vâ‚€t + Â½Â·aÂ·tÂ² and Î”v = aÂ·t (where s is the position, vâ‚€ is the speed at the start, a is the acceleration, and t is the elapsed time). You might declare the object as something like this:</p>
<pre class="brush: cpp; title: ; notranslate">

class PhysicsObject {
  public:
    float pos_x, pos_y, pos_z; // Position
    float vel_x, vel_y, vel_z; // Velocity
    float imass; // The inverse of the mass (1/m)

    void addImpulse(float force_x, float force_y, float force_z, float t) // t is time, in seconds
    {
        float halft2 = 0.5f * t * t;

        float accel_x = force_x * imass;
        float accel_y = force_y * imass;
        float accel_z = force_z * imass;

        pos_x += vel_x * t + accel_x * halft2;
        pos_x += vel_y * t + accel_y * halft2;
        pos_x += vel_z * t + accel_z * halft2;

        vel_x += accel_x * t;
        vel_y += accel_y * t;
        vel_z += accel_z * t;
    }
};

</pre>
<p>Not very pretty &#8211; there&#8217;s a lot of redundancy &#8211; whatever you do for one axis, you do for the other two. If only there was a way to do that all at once&#8230;</p>
<p><strong>Enter vectors: The Pretty Code<br />
</strong></p>
<p>Here&#8217;s the same code, but this time using a hypothetical 3d vector class:</p>
<pre class="brush: cpp; title: ; notranslate">

class PhysicsObject {
  public:
    vector3f pos; // Position
    vector3f vel; // Velocity
    float imass; // The inverse of the mass (1/m)

    void addImpulse(vector3f force, float t) // t is time, in seconds
    {
        vector3f accel = force * imass;
        pos += vel * t + accel * (0.5f * t * t);
        vel += accel * t;
    }
};

</pre>
<p>Much shorter, isn&#8217;t it? You now have half as many lines to write, test and debug. Not only that, but they&#8217;re also simpler, and you avoid a whole class of &#8220;copy-paste but oops forgot to change a letter in one place&#8221; bugs. So, after all, what ARE these vectors? How do they work?</p>
<p>P.S.: If you&#8217;re using a language which does not allow you to define your own operators, the code above will get quite uglier&#8230; Java, I&#8217;m looking at you.</p>
<p><strong>Defining vectors</strong></p>
<p>If you go check <a title="Euclidean Vector at Wikipedia" href="http://en.wikipedia.org/wiki/Euclidean_vector" target="_blank">Euclidean Vector at Wikipedia</a>, you&#8217;ll see that it&#8217;s defined as a geometric object that has magnitude (length) and direction. For our purposes, while important to remember that definition, we&#8217;ll think of vectors as an n-tuple of a given type. In the example about, we have a 3-tuple (&#8220;a triple&#8221;) of floats. In other words, our definition would be something like this:</p>
<pre class="brush: cpp; title: ; notranslate">

class vector3 {
  public:
    float x, y, z;

    inline vector3 operator + (const vector3 &amp;amp;param) const
    {
        return vector3(x + param.x, y + param.y, z + param.z);
    }

    inline vector3&amp;amp; operator += (const vector3 &amp;amp;param)
    {
        x += param.x;
        y += param.y;
        z += param.z;
        return *this;
    }

    inline vector3 operator * (float param) const
    {
        return vector3(x * param, y * param, z * param);
    }

    // Lots of other methods here
};

</pre>
<p>Basically, all it does (so far) is take basic arithmetic operators and apply them to 3 values, instead of just one. When you add two vectors, it adds each component &#8211; x to x, y to y and z to z. There&#8217;s also the &#8220;scale&#8221; operator, which is the multiplication by a scalar (a scalar is a non-vectorial number, like a float). When you multiply a vector by a scalar, you simply multiply all components by it. So, if you want to make your vector twice as big, just multiply it by 2.</p>
<p>That&#8217;s it! That&#8217;s the basic idea! Whenever you have two or more points and always want to perform the same set of operations on them, use a vector! In fact, most properties that apply to scalar numbers will also work here&#8230; If you happen to know that you need to multiply velocity by time to get a change in position, you can do that with vectors in just the same way you would with scalars.</p>
<p>When should you use vectors like this? <em>Whenever it makes sense</em>. If you&#8217;re passing along two or three values which all represent the same point, do yourself a favor and pack them in a vector. Not only will it be much harder to accidentally mix up stuff, your code will be shorter. Even if they aren&#8217;t a POSITION, they might still be represented by a vector &#8211; for example, the size of a rectangle is a vector where x is the width and y is the height. That way, if you have a vector representing the starting position of the rectangle, and a vector representing its size, you can easily find its ending position by adding them up.</p>
<p>But vectors are far more powerful than this. On the next article, we&#8217;ll explore other common operations done on them, such as length, normalization, dot product and cross product. You wouldn&#8217;t believe me if I told you just how damn useful those can be.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-02-vectors-101/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Math for game programmers 01 &#8211; Introduction</title>
		<link>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-01-introduction/</link>
		<comments>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-01-introduction/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 06:51:02 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[math]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://higherorderfun.wordpress.com/?p=13</guid>
		<description><![CDATA[Here comes a harsh fact of life: game programming requires mathematics. One could say that programming IS, in a way, math, but you don&#8217;t really need to know math to write the vast majority of programs. Most of the time, you don&#8217;t need it to write parsers, to interact with databases, to validate data. Games, [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Here comes a harsh fact of life: game programming requires mathematics. One could say that programming IS, in a way, math, but you don&#8217;t really need to know math to write the vast majority of programs. Most of the time, you don&#8217;t need it to write parsers, to interact with databases, to validate data. Games, however, very often rely on mathematics. If you want objects to move across your world realistically, or if you want to draw things on the screen following certain geometric patterns, or if you want to check for collision between certain shapes, you need math.</p>
<p>But don&#8217;t despair! Even though I say &#8220;math&#8221;, what you ACTUALLY need is geometry. Luckily for us, geometry is probably the easiest part of mathematics! Now, I&#8217;m not saying that discrete mathematics, algebra and calculus are useless for writing games (or other sorts of programs), but geometry is the bread and butter of video game programmers.</p>
<p>An interesting thing that I did notice is that, despite my previous assertion, many game programmers do not actually know much geometry! This means that they&#8217;ll often do things in extremely laborious, buggy and verbose ways, when it could very easily be done with some basic grasp of geometry. For example, if you want to place several objects along an arc of circle, you COULD do it through trial and error, or place it in an image editing program (like Photoshop) and copying the coordinates, but it will be much easier if you simply use a parametric equation.</p>
<p>So I intend to write a few posts to explain, as clearly as I can, some topics that are important to game programming. These are the topics that I intend to cover:</p>
<ul>
<li>Vectors</li>
<li>Parametric Equations</li>
<li>Vector bases</li>
<li>Basic Trigonometry</li>
<li>Matrices</li>
<li>Complex Numbers</li>
<li>Quaternions</li>
</ul>
<p>While there are many basic and in-depth tutorials of all of the above topics on the Internet, explanations as to why the matter to game programmers and how to use them seem to be scarce, or left as an exercise to the reader. My goal is to make those topics easy to understand and put into use.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-01-introduction/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
	</channel>
</rss>
