tag:blogger.com,1999:blog-7847112223123423582024-02-18T21:48:23.313-08:00Hand picked articles on Flash Development and Software Design<p align="center"><strong>Best articles on Flash Development and Software Design</strong></p>Unknownnoreply@blogger.comBlogger454125tag:blogger.com,1999:blog-784711222312342358.post-32416572073377904712013-05-21T12:40:00.001-07:002013-05-21T12:41:00.708-07:00Let’s Build a 3D Graphics Engine: Points, Vectors, and Basic Concepts<div>This entry is part 1 of 1 in the series <a href="http://gamedev.tutsplus.com/series/3d-graphics-engine/" title="Let's Build a 3D Graphics Engine">Let's Build a 3D Graphics Engine</a></div>The 3D game engines that are behind today’s biggest games are staggering works of mathematics and programming, and many game developers find that understanding them in their entirety is a difficult task. If you are lacking in experience (or a college degree like myself), this task becomes even more arduous. In this series, I aim to walk you through the basics of graphics systems in 3D engines. More specifically, in this tutorial we will be discussing points and vectors, and all of the fun that comes with them. If you have a basic grasp of algebra (variables and variable math) and Computer Science (the basics of any object-oriented programming language), you should be able to make it through most of these tutorials, but if you’re having trouble with any of the concepts, please ask questions! Some of these topics can be terribly difficult. <br />
<hr /><h2>Basics of Coordinate Systems</h2>Let’s start from the basics. Three-dimensional graphics require the concept of a three-dimensional space. The most widely used of these spaces is called the Cartesian Space, which gives us the benefit of Cartesian coordinates (the basic \((x,y)\) notations and 2D grid-spaced graphs that are taught in most high schools). <img alt="Build a 3D Graphics Engine tutorial" height="242" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image001.png" width="241" /> Pictured: the bane of many high schoolers’ existence. 3-dimensional Cartesian space gives us an x, y, and z axis (describing position based on horizontal placement, vertical placement, and depth respectively). The coordinates for any point within this space are shown as a <i>tuple</i> (in this case a 3-tuple, since there are three axes). On a 2-dimensional plane, a tuple could be depicted as \((x,y)\), and in 3-dimensional plane, it is depicted as \((x,y,z)\). The use of this 3-tuple is that it shows a point’s location relative to the space’s origin (which itself is typically shown as \((0,0,0)\)). <b>Tip:</b> Tuple: an ordered list (or sequence) of elements in computer science or mathematics. So, \((K,y,l,e)\) would be a 4-tuple, showing a sequence of characters that make up my name. <img alt="Build a 3D Graphics Engine tutorial" height="350" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image002.png" width="361" /> Within this space, we are going to define a point as a representation of a 3-tuple. This can also be shown as: \[P = (x,y,z)\] In addition to this definition of a point, we must define its parts. Each of the elements within this 3-tuple is a <i>scalar</i> (number) that defines a position along a <i>basis vector</i>. Each basis vector must have a unit length (that is, a length of exactly 1), so 3-tuples such as \((1,1,1)\) and \((2,2,2)\) could not be basis vectors as they are too long. We define three basis vectors for our space: \[\begin{aligned} X & = (1,0,0)\\ Y & = (0,1,0)\\ Z & = (0,0,1) \end{aligned}\] <img alt="Build a 3D Graphics Engine tutorial" height="295" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image003.jpg" width="315" /> Source: <a href="javascript:void(0);">http://www.thefullwiki.org/Arithmetics/Cartesian_Coordinate</a>. <br />
<hr /><h2>The Coordinate System</h2>Now let’s talk about the mathematical definition of our coordinate system, how it affects our graphics system, and the calculations we can make. <br />
<h3>Representing Points</h3>The <i>origin point</i> of our coordinate system can be depicted as the point \(O\), which represents the 3-tuple (0,0,0). This means that the mathematical representation of our coordinate system can be depicted as: \[\{O;X,Y,Z\}\] By this statement, you can say that \((x,y,z)\) represents a point’s position in relation to the origin. This definition also means that any point \(P\), \((a, b, c)\), can be represented as: \[P = O + aX + bY + cZ\] From here on, I will reference scalars in lower-case and vectors in upper-case – so \(a\), \(b\), and \(c\) are scalars, and \(X\), \(Y\), and \(Z\) are vectors. (They are actually the basis vectors we defined earlier.) This means that a point whose tuple is (2,3,4) could be represented as: \[\begin{aligned} (2,3,4) & = (2,0,0) + (0,3,0) + (0,0,4)\\ & = (0,0,0) + (2,0,0) + (0,3,0) + (0,0,4)\\ & = (0,0,0) + 2(1,0,0) + 3(0,1,0) + 4(0,0,1)\\ & = O + 2X + 3Y + 4Z\\ \end{aligned}\] So, we’ve taken this abstract concept of “a point in 3D space” and defined it as four separate objects added together. This kind of definition is very important whenever we want to put any concept into code. <br />
<h3>Mutually Perpendicular</h3>The coordinate system that we will be using also has the valuable property of being <i>mutually perpendicular</i>. This means that there is a 90 degree angle between each of the axes where they meet on their respective planes. <img alt="Build a 3D Graphics Engine tutorial" height="337" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image0031.jpg" width="337" /> Our coordinate system will also be defined as “right-handed”: <img alt="Build a 3D Graphics Engine tutorial" height="189" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image004.jpg" width="253" /> Source: <a href="http://viz.aset.psu.edu/gho/sem_notes/3d_fundamentals/html/3d_coordinates.html">http://viz.aset.psu.edu/gho/sem_notes/3d_fundamentals/html/3d_coordinates.html</a>. In mathematical terms, this means that: \[X = Y \times Z\] …where \(\times\) represents the cross product operator. In case you aren’t sure what a cross product is, it can be defined by the following equation (assuming you are given two 3-tuples): \[(a,b,c) \times (d,e,f) = (bf - ce, cd - af, ae - bd)\] These statements might seem tedious, but later on, they will allow us to do a variety of different calculations and transformations much more easily. Luckily, you don’t have to memorize all of these equations when building a game engine – you can simply build from these statements, and then build even less complicated systems on top of that. Well, until you have to edit something fundamental within your engine and have to refresh yourself on all of this again! <br />
<hr /><h2>Points and Vectors</h2>With all of the basics of our coordinate system locked down, its time to talk about points and vectors and, more importantly, how they interact with one another. The first thing to note is that points and vectors are distinctly different things: a point is a physical location within your space; a vector is the space between two points. <img alt="Build a 3D Graphics Engine tutorial" height="246" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/05/image006.png" width="274" /> To make sure that the two don’t get confused, I’ll write points in capital italics, as \(P\), and vectors in capital boldface, as \(\mathbf{V}\). There are two main axioms that we are going to deal with when using points and vectors, and they are: <br />
<ul><li>Axiom 1: The difference of two points is a vector, so \(\mathbf{V} = P – Q\)</li>
<li>Axiom 2: The sum of a point and a vector is a point, so \(Q = P + \mathbf{V}\)</li>
</ul><b>Tip:</b> An <i>axiom</i> is a point of reasoning, often seen as evident enough to be accepted without argument.<br />
<hr /><h2>Building the Engine</h2>With these axioms stated, we now have enough information to create the building block classes that are at the heart of any 3D game engine: the <code>Point</code> class and the <code>Vector</code> class. If we were going to build our own engine using this information, there would be some other important steps to take when creating these classes (mostly having to do with optimization or dealing with already existing APIs), but we are going to leave these out for the sake of simplicity. The class examples below are all going to be in pseudocode so that you can follow along with your programming language of choice. Here are outlines of our two classes: <br />
<pre>Point Class
{
Variables:
num tuple[3]; //(x,y,z)
Operators:
Point AddVectorToPoint(Vector);
Point SubtractVectorFromPoint(Vector);
Vector SubtractPointFromPoint(Point);
Function:
//later this will call a function from a graphics API, but for now
//this should just be printing the points coordinates to the screen
drawPoint;
}
</pre><pre>Vector Class
{
Variables:
num tuple[3]; //(x,y,z)
Operators:
Vector AddVectorToVector(Vector);
Vector SubtractVectorFromVector(Vector);
}
</pre><br />
[...] <br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/lets-build-a-3d-graphics-engine-points-vectors-and-basic-concepts/" target="_blank">Read more: Let’s Build a 3D Graphics Engine: Points, Vectors, and Basic Concepts</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-76890656457117836182013-05-01T10:01:00.001-07:002013-05-01T10:02:06.760-07:00How to Create a Custom 2D Physics Engine: The Core Engine<div>This entry is part 2 of 2 in the series <a href="http://gamedev.tutsplus.com/series/custom-game-physics-engine/" title="How to Create a Custom Physics Engine">How to Create a Custom Physics Engine</a></div>In this part of my series on creating a custom 2D physics engine for your games, we’ll add more features to the impulse resolution we got working in the first part. In particular, we’ll look at integration, timestepping, using a modular design for our code, and broad phase collision detection.<br />
<hr /><h2>Introduction</h2>In the last post in this series I covered the topic of <a href="http://gamedev.tutsplus.com/tutorials/implementation/create-custom-2d-physics-engine-aabb-circle-impulse-resolution/">impulse resolution</a>. Read that first, if you haven’t already!<br />
Let’s dive straight into the topics covered in this article. These topics are all of the necessities of any half-decent physics engine, so now is an appropriate time to build more features on top of the core resolution from the last article.<br />
<ul><li><a href="http://gamedev.tutsplus.com/#integration">Integration</a></li>
<li><a href="http://gamedev.tutsplus.com/#timestepping">Timestepping</a></li>
<li><a href="http://gamedev.tutsplus.com/#modulardesign">Modular Design</a><ul><li>Bodies</li>
<li>Shapes</li>
<li>Forces</li>
<li>Materials</li>
</ul></li>
<li><a href="http://gamedev.tutsplus.com/#broadphase">Broad Phase</a><ul><li>Contact pair duplicate culling</li>
<li>Layering</li>
</ul></li>
<li><a href="http://gamedev.tutsplus.com/#halfspace">Halfspace Intersection Test</a></li>
</ul><hr /><h2><a href="http://www.blogger.com/blog-this.g" name="integration">Integration</a></h2>Integration is entirely simple to implement, and there are very many areas on the internet that provide good information for iterative integration. This section will mostly show how to implement a proper integration function, and point to some different locations for further reading, if desired.<br />
First it should be known what acceleration actually is. <a href="http://en.wikipedia.org/wiki/Newton%27s_laws_of_motion">Newton’s Second Law</a> states:<br />
\[Equation 1:\\<br />
F = ma\]<br />
This states that the sum of all forces acting upon some object is equal to that object’s mass <code>m</code> multiplied by its acceleration <code>a</code>. <code>m</code> is in kilograms, <code>a</code> is in meters/second, and <code>F</code> is in Newtons.<br />
Rearranging this equation a bit to solve for <code>a</code> yields:<br />
\[Equation 2:\\<br />
a = \frac{F}{m}\\<br />
\therefore\\<br />
a = F * \frac{1}{m}\]<br />
The next step involves using acceleration to step an object from one location to another. Since a game is displayed in discrete separate frames in an illusion-like animation, the locations of each position at these discrete steps has to be calculated. For a more in-depth cover of these equations please see: <a href="https://code.google.com/p/box2d/downloads/detail?name=GDC2009_ErinCatto.zip&can=2&q=">Erin Catto’s Integration Demo from GDC 2009</a> and <a href="http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html">Hannu’s addition to symplectic Euler for more stability in low FPS environments</a>.<br />
Explicit Euler (pronounced “oiler”) integration is shown in the following snippet, where <code>x</code> is position and <code>v</code> is velocity. Please note that <code>1/m * F</code> is acceleration, as explained above:<br />
<pre>// Explicit Euler
x += v * dt
v += (1/m * F) * dt
</pre><code>dt</code> here refers to delta time. Δ is the symbol for delta, and can be read literally as “change in”, or written as Δ<code>t</code>. So whenever you see <code>dt</code> it can be read as “change in time”. <code>dv</code> would be “change in velocity”.This will work, and is commonly used as a starting point. However, it has numerical inaccuracies that we can get rid of without any extra effort. Here is what is known as Symplectic Euler:<br />
<pre>// Symplectic Euler
v += (1/m * F) * dt
x += v * dt
</pre>Note that all I did was rearrange the order of the two lines of code – see <a href="javascript:void(0);">“>the aforementioned article from Hannu</a>.<br />
This post explains the numerical inaccuracies of Explicit Euler, but be warned that he starts covering RK4, which I don’t personally recommend: <a href="http://gafferongames.com/game-physics/integration-basics/">gafferongames.com: Euler Inaccuracy</a>.<br />
These simple equations are all that we need to move all objects around with linear velocity and acceleration.<br />
<hr /><h2><a href="http://www.blogger.com/blog-this.g" name="timestepping">Timestepping</a></h2>Since games are displayed at discrete time intervals, there needs to be a way of manipulating the time between these steps in a controlled manner. Have you ever seen a game that will run at different speeds depending on what computer it is being played on? That’s an example of a game running at a speed dependent on the computer’s ability to run the game.<br />
We need a way to ensure that our physics engine only runs when a specific amount of time has passed. This way, the <code>dt</code> that is used within calculations is always the exact same number. Using the exact same <code>dt</code> value in your code everywhere will actually make your physics engine <i>deterministic</i>, and is known as a <i>fixed timestep</i>. This is a good thing.<br />
A deterministic physics engine is one that will always do the exact same thing every time it is run assuming the same inputs are given. This is essential for many types of games where gameplay needs to be very fine-tuned to the physics engine’s behavior. This is also essential for debugging your physics engine, as in order to pinpoint bugs the behavior of your engine needs to be consistent.<br />
Let’s first cover a simple version of a fixed timestep. Here is an example:<br />
<pre>const float fps = 100
const float dt = 1 / fps
float accumulator = 0
// In units of seconds
float frameStart = GetCurrentTime( )
// main loop
while(true)
const float currentTime = GetCurrentTime( )
// Store the time elapsed since the last frame began
accumulator += currentTime - frameStart( )
// Record the starting of this frame
frameStart = currentTime
while(accumulator > dt)
UpdatePhysics( dt )
accumulator -= dt
RenderGame( )
</pre>This waits around, rendering the game, until enough time has elapsed to update the physics. The elapsed time is recorded, and discrete <code>dt</code>-sized chunks of time are taken from the accumulator and processed by the physics. This ensures that the exact same value is passed to the physics no matter what, and that the value passed to the physics is an accurate representation of actual time that passes by in real life. Chunks of <code>dt</code> are removed from the <code>accumulator</code> until the <code>accumulator</code> is smaller than a <code>dt</code> chunk.<br />
There are a couple of problems that can be fixed here. The first involves how long it takes to actually perform the physics update: What if the physics update takes too long and the <code>accumulator</code> goes higher and higher each game loop? This is called the spiral of death. If this is not fixed, your engine will quickly grind to a complete halt if your physics cannot be performed fast enough.<br />
To solve this, the engine really needs to just run fewer physics updates if the <code>accumulator</code> gets too high. A simple way to do this would be to clamp the <code>accumulator</code> below some arbitrary value.<br />
<pre>const float fps = 100
const float dt = 1 / fps
float accumulator = 0
// In units seconds
float frameStart = GetCurrentTime( )
// main loop
while(true)
const float currentTime = GetCurrentTime( )
// Store the time elapsed since the last frame began
accumulator += currentTime - frameStart( )
// Record the starting of this frame
frameStart = currentTime
// Avoid spiral of death and clamp dt, thus clamping
// how many times the UpdatePhysics can be called in
// a single game loop.
if(accumulator > 0.2f)
accumulator = 0.2f
while(accumulator > dt)
UpdatePhysics( dt )
accumulator -= dt
RenderGame( )
</pre>Now, if a game running this loop ever encounters some sort of stalling for whatever reason, the physics will not drown itself in a spiral of death. The game will simply run a little more slowly, as appropriate.<br />
The next thing to fix is quite minor in comparison to the spiral of death. This loop is taking <code>dt</code> chunks from the <code>accumulator</code> until the <code>accumulator</code> is smaller than <code>dt</code>. This is fun, but there’s still a little bit of remaining time left in the <code>accumulator</code>. This poses a problem.<br />
Assume the <code>accumulator</code> is left with 1/5th of a <code>dt</code> chunk every frame. On the sixth frame the <code>accumulator</code> will have enough remaining time to perform one more physics update than all the other frames. This will result in one frame every second or so performing a slightly larger discrete jump in time, and might be very noticeable in your game.<br />
To solve this, the use of <i>linear interpolation</i> is required. If this sounds scary, don’t worry – the implementation will be shown. If you want to understand the implementation there are many resources online for linear interpolation.<br />
<pre>// linear interpolation for a from 0 to 1
// from t1 to t2
t1 * a + t2(1.0f - a)
</pre>Using this we can interpolate (approximate) where we might be between two different time intervals. This can be used to render the state of a game in between two different physics updates.<br />
With linear interpolation, the rendering of an engine can run at a different pace than the physics engine. This allows a graceful handling of the leftover <code>accumulator</code> from the physics updates.<br />
Here is a full example:<br />
<pre>const float fps = 100
const float dt = 1 / fps
float accumulator = 0
// In units seconds
float frameStart = GetCurrentTime( )
// main loop
while(true)
const float currentTime = GetCurrentTime( )
// Store the time elapsed since the last frame began
accumulator += currentTime - frameStart( )
// Record the starting of this frame
frameStart = currentTime
// Avoid spiral of death and clamp dt, thus clamping
// how many times the UpdatePhysics can be called in
// a single game loop.
if(accumulator > 0.2f)
accumulator = 0.2f
while(accumulator > dt)
UpdatePhysics( dt )
accumulator -= dt
const float alpha = accumulator / dt;
RenderGame( alpha )
void RenderGame( float alpha )
for shape in game do
// calculate an interpolated transform for rendering
Transform i = shape.previous * alpha + shape.current * (1.0f - alpha)
shape.previous = shape.current
shape.Render( i )
</pre>Here, all objects within the game can be drawn at variable moments between discrete physics timesteps. This will gracefully handle all error and remainder time accumulation. This is actually rendering ever so slightly behind what the physics has currently solved for, but when watching the game run all motion is smoothed out perfectly by the interpolation.<br />
The player will never know that the rendering is ever so slightly behind the physics, because the player will only know what they see, and what they’ll see is perfectly smooth transitions from one frame to another.<br />
You may be wondering, “why don’t we interpolate from the current position to the next?”. I tried this and it requires the rendering to “guess” where objects are going to be in the future. Often, objects in a physics engine make sudden changes in movement, such as during collision, and when such a sudden movement change is made, objects will teleport around due to inaccurate interpolations into the future.<br />
<hr /><h2><a href="http://www.blogger.com/blog-this.g" name="modulardesign">Modular Design</a></h2>There are a few things every physics object is going to need. However, the specific things each physics object needs may change slightly from object to object. A clever way to organize all this data is required, and it would be assumed that the lesser amount of code to write to achieve such organization is desired. In this case some modular design would be of good use.<br />
Modular design probably sounds a little pretentious or over-complicated, but it does make sense and is quite simple. In this context, “modular design” just means we want to break a physics object into separate pieces, so that we can connect or disconnect them however we see fit.<br />
<h3>Bodies</h3>A physics body is an object that contains all information about some given physics object. It will store the shape(s) that the object is represented by, mass data, transformation (position, rotation), velocity, torque, and so on. Here is what our <code>body</code> ought to look like:<br />
<pre>struct body
{
Shape *shape;
Transform tx;
Material material;
MassData mass_data;
Vec2 velocity;
Vec2 force;
real gravityScale;
};
</pre>This is a great starting point for the design of a physics body structure. There are some intelligent decisions made here that tend towards strong code organization.<br />
The first thing to notice is that a shape is contained within the body by means of a pointer. This represents a loose relationship between the body and its shape. A body can contain any shape, and the shape of a body can be swapped around at will. In fact, a body can be represented by multiple shapes, and such a body would be known as a “composite”, as it would be composed of multiple shapes. (I’m not going to cover composites in this tutorial.)<br />
<img alt="Body and Shape interface." height="400" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/uploads/2013/04/custom-physics-shape-interface.png" width="600" /><br />
Body and Shape interface. The <code>shape</code> itself is responsible for computing bounding shapes, calculating mass based on density, and rendering.<br />
The <code>mass_data</code> is a small data structure to contain mass-related information:<br />
<pre>struct MassData
{
float mass;
float inv_mass;
// For rotations (not covered in this article)
float inertia;
float inverse_inertia;
};
</pre>It is nice to store all mass- and intertia-related values in a single structure. The mass should never be set by hand – mass should always be calculated by the shape itself. Mass is a rather unintuitive type of value, and setting it by hand will take a lot of tweaking time. It’s defined as:<br />
\[ Equation 3:\\Mass = density * volume\]<br />
Whenever a designer wants a shape to be more “massive” or “heavy”, they should modify the density of a shape. This density can be used to calculate the mass of a shape given its volume. This is the proper way to go about the situation, as density is not affected by volume and will never change during the runtime of the game (unless specifically supported with special code).<br />
Some examples of shapes such as AABBs and Circles can be found in <a href="http://gamedev.tutsplus.com/tutorials/implementation/create-custom-2d-physics-engine-aabb-circle-impulse-resolution/">the previous tutorial in this series</a>.<br />
<h3>Materials</h3>All this talk of mass and density leads to the question: Where does the density value lay? It resides within the <code>Material</code> structure:<br />
<pre>struct Material
{
float density;
float restitution;
};
</pre>Once the values of the material are set, this material can be passed to the shape of a body so that the body can calculate the mass [...]<br />
<br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/how-to-create-a-custom-2d-physics-engine-the-core-engine/" target="_blank">Read more: How to Create a Custom 2D Physics Engine: The Core Engine</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-1232594432949597022013-04-08T14:39:00.001-07:002013-04-08T14:40:14.182-07:00Tutorial: Debugging Native ExtensionsI've written before about how to create your <a href="http://rhuno.com/flashblog/2012/04/30/tutorial-flash-and-c-native-extension/">own native extensions</a> for Adobe AIR, but what if you need to debug your extension? If you're doing anything but the simplest of projects, you're going to want to be able to debug the code on the native side, in addition to your AS3 code. The ActionScript side is (hopefully!) already taken care of by your IDE so this tutorial will focus on the native code. It's a pretty short tutorial, but also incredibly useful! For this tutorial, I'm using Visual Studio 2012 Express, which you can <a href="http://www.microsoft.com/visualstudio/eng/downloads#d-express-windows-desktop">get for free</a> from Microsoft and a slightly modified version of the NativeAdd extension from the tutorial linked above. First, you'll want to have your AIR project running. Then switch over to Visual Studio and set a break point (f9 or click the side bar) on the line you want to investigate (shown below). <a href="http://rhuno.com/flashblog/wp-content/uploads/2013/04/bpSet.jpg"><img alt="" height="238" src="http://rhuno.com/flashblog/wp-content/uploads/2013/04/bpSet.jpg" title="bpSet" width="673" /></a> Next, select Debug > Attach to Process from the Visual Studio menu. If you're using Visual Studio 2010 and you don't see this option, first click Tools > Settings > Expert Settings. <a href="http://rhuno.com/flashblog/wp-content/uploads/2013/04/atp1.jpg"><img alt="" height="386" src="http://rhuno.com/flashblog/wp-content/uploads/2013/04/atp1.jpg" title="atp1" width="416" /></a> This will bring up a window with a list of running processes on your PC. In this list find the adl.exe process, select it and click the Attach button. <a href="http://rhuno.com/flashblog/wp-content/uploads/2013/04/atp2.jpg"><img alt="" height="437" src="http://rhuno.com/flashblog/wp-content/uploads/2013/04/atp2.jpg" title="atp2" width="688" /></a> Once the debugger has attached itself to the process, go back to your AIR application and have it call into the native function where you added your break point. In this case, I'm using the NativeAdd extension from a previous tutorial. I modified it a bit so that when the stage is clicked, it calls the doAdd function on the native side. With the debugger attached, when I click the stage, my breakpoint gets hit as shown here: <a href="http://rhuno.com/flashblog/wp-content/uploads/2013/04/bpHit.jpg"><img alt="" height="233" src="http://rhuno.com/flashblog/wp-content/uploads/2013/04/bpHit.jpg" title="bpHit" width="677" /></a> You can now take a look at the values of your native code variables and monitor them as you step through the code using the Visual Studio debugger tools. Here's a sample shot of the watch window with the NativeAdd extension. <a href="http://rhuno.com/flashblog/wp-content/uploads/2013/04/varValues.jpg"><img alt="" height="182" src="http://rhuno.com/flashblog/wp-content/uploads/2013/04/varValues.jpg" title="varValues" width="562" /></a> <br />
[...] <a href="http://rhuno.com/flashblog/2013/04/07/tutorial-debugging-native-extensions/" target="_blank">Read more: Tutorial: Debugging Native Extensions</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-19584908787615311362013-04-06T13:30:00.001-07:002013-04-06T13:31:12.105-07:00How to Create a Custom 2D Physics Engine: The Basics and Impulse ResolutionThere are many reasons you might want to create a custom physics engine: first, learning and honing your skills in mathematics, physics and programming are great reasons to attempt such a project; second, a custom physics engine can tackle any sort of technical effect the creator has the skill to create. In this article I would like to provide a solid introduction on how to create a custom physics engine entirely from scratch. Physics provides a wonderful means for allowing a player to immerse themselves within a game. It makes sense that a mastery of a physics engine would be a powerful asset for any programmer to have at their disposal. Optimizations and specializations can be made at any time due to a deep understanding of the inner workings of the physics engine. By the end of this tutorial the following topics will have been covered, in two dimensions: <br />
<ul><li>Simple collision detection</li>
<li>Simple manifold generation</li>
<li>Impulse resolution</li>
</ul>Here’s a quick demo: <iframe frameborder="0" height="338" src="http://www.youtube.com/embed/bjmbh_0FzZ0" width="600"></iframe> <br />
<hr /><h2>Prerequisites</h2>This article involves a fair amount of mathematics and geometry, and to a much lesser extent actual coding. A couple prerequisites for this article are: <br />
<ul><li>A basic understanding of simple vector math</li>
<li>The ability to perform algebraic math</li>
</ul><hr /><h2>Collision Detection</h2>There are quite a few articles and tutorials throughout the internet, including here on Tuts+, that cover collision detection. Knowing this, I would like to run through the topic very quickly as this section is not the focus of this article. <br />
<h3>Axis Aligned Bounding Boxes</h3>An Axis Aligned Bounding Box (AABB) is a box that has its four axes aligned with the coordinate system in which it resides. This means it is a box that cannot rotate, and is always squared off at 90 degrees (usually aligned with the screen). In general it is referred to as a “bounding box” because AABBs are used to bound other more complex shapes. <img alt="An example AABB." height="400" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/randy-gaul/custom-physics-aabb.png" width="600" /> An example AABB. The AABB of a complex shape can be used as a simple test to see if more complex shapes inside the AABBs can possibly be intersecting. However in the case of most games the AABB is used as a fundamental shape, and does not actually bound anything else. The structure of your AABB is important. There are a few different ways to represent an AABB, however this is my favorite: <br />
<pre>struct AABB
{
Vec2 min;
Vec2 max;
};
</pre>This form allows an AABB to be represented by two points. The min point represents the lower bounds of the x and y axis, and max represents the higher bounds – in other words, they represent the top left and bottom right corners. In order to tell whether two AABB shapes are intersecting you will need to have a basic understanding of the <a href="http://gamedev.tutsplus.com/tutorials/implementation/collision-detection-with-the-separating-axis-theorem/">Separating Axis Theorem</a> (SAT). Here’s a quick test taken from <a href="http://realtimecollisiondetection.net/">Real-Time Collision Detection</a> by Christer Ericson, which makes use of the SAT: <br />
<pre>bool AABBvsAABB( AABB a, AABB b )
{
// Exit with no intersection if found separated along an axis
if(a.max.x < b.min.x or a.min.x > b.max.x) return false
if(a.max.y < b.min.y or a.min.y > b.min.y) return false
// No separating axis found, therefor there is at least one overlapping axis
return true
}
</pre><h3>Circles</h3>A circle is represented by a radius and point. Here is what your circle structure ought to look like: <br />
<pre>struct Circle
{
float radius
Vec position
};
</pre>Testing for whether or not two circles intersect is very simple: take the radii of the two circles and add them together, then check to see if this sum is greater than the distance between the two circles. An important optimization to make here is get rid of any need to use the square root operator: <br />
<pre>float Distance( Vec2 a, Vec2 b )
{
return sqrt( (a.x + b.x)^2 + (a.y + b.y)^2 )
}
bool CirclevsCircleUnoptimized( Circle a, Circle b )
{
float r = a.radius + b.radius
return r < Distance( a.position, b.position )
}
bool CirclevsCircleOptimized( Circle a, Circle b )
{
float r = a.radius + b.radius
r *= r
return r < (a.x + b.x)^2 + (a.y + b.y)^2
}
</pre>In general multiplication is a much cheaper operation than taking the square root of a value. <br />
<hr /><h2>Impulse Resolution</h2>Impulse resolution is a particular type of collision resolution strategy. Collision resolution is the act of taking two objects who are found to be intersecting and modifying them in such a way as to not allow them to remain intersecting. In general an object within a physics engine has two main <a href="http://en.wikipedia.org/wiki/Degrees_of_freedom_(mechanics)">degrees of freedom</a> (in two dimensions): movement in the xy plane and rotation. In this article we implicitly restrict rotation and use just AABBs and Circles, so the only degree of freedom we really need to consider is movement along the xy plane. By resolving detected collisions we place a restriction upon movement such that objects cannot remain intersecting one another. The idea behind impulse resolution is to use an impulse (instantaneous change in velocity) to separate objects found colliding. In order to do this the mass, position, and velocity of each object must be taken into account somehow: we want large objects colliding with smaller ones to move a little bit during collision, and to send the small objects flying away. We also want objects with infinite mass to not move at all. <img alt="Simple example of what impulse resolution can achieve." height="400" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/randy-gaul/custom-physics-resolution-example.png" width="600" /> Simple example of what impulse resolution can achieve. In order to achieve such effects and follow along with natural intuition of how objects behave we’ll use rigid bodies and a fair bit of math. A rigid body is just a shape defined by the user (that is, by you, the developer) that is implicitly defined to be non-deformable. Both AABBs and Circles in this article are non-deformable, and will always be either an AABB or Circle. No squashing or stretching allowed. Working with rigid bodies allows for a lot of math and derivations to be heavily simplified. This is why rigid bodies are commonly used in game simulations, and why we’ll be using them in this article. <br />
<h3>Our Objects Collided – Now What?</h3>Assuming we have two shapes found to be intersecting, how does one actually separate the two? Lets assume our collision detection provided us with two important pieces of information: <br />
<ul><li>Collision normal</li>
<li>Penetration depth</li>
</ul>In order to apply an impulse to both objects and move them apart, we need to know what direction to push them and by how much. The collision normal is the direction in which the impulse will be applied. The penetration depth (along with some other things) determine how large of an impulse will be used. This means the only value that needs to be solved for is the magnitude of our impulse. Now let’s go on a long trek to discover how we can solve for this impulse magnitude. We’ll start with our two objects that have been found to be intersecting: <br />
<div align="center"><i>Equation 1</i></div>\[ V^{AB} = V^B - V^A \] Note that in order to create a vector from position A to position B, you must do: <code>endpoint - startpoint</code>. \(V^{AB}\) is the relative velocity from A to B. This equation ought to be expressed in terms of the collision normal \(n\) – that is, we would like to know the relative velocity from A to B along the collision normal’s direction: <br />
<div align="center"><i>Equation 2</i></div>\[ V^{AB} \cdot n = (V^B - V^A) \cdot n \] We are now making use of the <a href="http://en.wikipedia.org/wiki/Dot_product">dot product</a>. The dot product is simple; it is the sum of component-wise products: <br />
<div align="center"><i>Equation 3</i></div>\[ V_1 = \begin{bmatrix}x_1 \\y_1\end{bmatrix}, V_2 = \begin{bmatrix}x_2 \\y_2\end{bmatrix} \\ V_1 \cdot V_2 = x_1 * x_2 + y_2 * y_2 \] The next step is to introduce what is called the <i>coefficient of restitution</i>. Restitution is a term that means elasticity, or bounciness. Each object in your physics engine will have a restitution represented as a decimal value. However only one decimal value will be used during the impulse calculation. To decide what restitution to use (denoted by \(e\) for epsilon), you should always use the lowest restitution involved in the collision for intuitive results: <br />
<pre>// Given two objects A and B
e = min( A.restitution, B.restitution )
</pre>Once \(e\) is acquired we can place it into our equation solving for the impulse magnitude. Newton’s Law of Restitution states the following: <br />
<div align="center"><i>Equation 4</i></div>\[V' = e * V \] All this is saying is that the velocity after a collision is equal to the velocity before it, multiplied by some constant. This constant represents a “bounce factor”. Knowing this, it becomes fairly simple to integrate restitution into our current derivation: <br />
<div align="center"><i>Equation 5</i></div>\[ V^{AB} \cdot n = -e * (V^B - V^A) \cdot n \] Notice how we introduced a negative sign here. In Newton’s Law of Restitution, \(V’\), the resulting vector after the bounce, is actually going in the opposite direction of V. So how do we represent opposite directions in our derivation? Introduce a negative sign. So far so good. Now we need to be able to express these velocities while under the influence of an impulse. Here’s a simple equation for modify a vector by some impulse scalar \(j\) along a specific direction \(n\): <br />
<div align="center"><i>Equation 6</i></div>\[ V' = V + j * n \] Hopefully the above equation makes sense, as it is very important to understand. We have a unit vector \(n\) which represents a direction. We have a scalar \(j\) which represents how long our \(n\) vector will be. We then add our scaled \(n\) vector to \(V\) to result in \(V’\). This is just adding one vector onto another, and we can use this small equation to apply an impulse of one vector to another. There’s a little more work to be done here. Formally, an impulse is defined as a change in momentum. Momentum is <code>mass * velocity</code>. Knowing this, we can represent an impulse as it is formally defined like so: <br />
<div align="center"><i>Equation 7</i></div>\[ Impulse = mass * Velocity \\ Velocity = \frac{Impulse}{mass} \therefore V' = V + \frac{j * n}{mass}\] The three dots in a small triangle (\(\therefore\)) can be read as “therefore”. It is used to show that the thing beforehand can be used to conclude that whatever comes next is true. Good progress has been made so far! However we need to be able to express an impulse using \(j\) in terms of two different objects. During a collision with object A and B, A will be pushed in the opposite direction of B: <br />
<div align="center"><i>Equation 8</i></div>\[ V'^A = V^A + \frac{j * n}{mass^A} \\ V'^B = V^B - \frac{j * n}{mass^B} \] These two equations will push A away from B along the direction unit vector \(n\) by impulse scalar (magnitude of \(n\)) \(j\). All that is now required is to merge Equations 8 and 5. Our resulting equation will look something like this: <br />
<div align="center"><i>Equation 9</i></div>\[ (V^A - V^V + \frac{j * n}{mass^A} + \frac{j * n}{mass^B}) * n = -e * (V^B - V^A) \cdot n \\ \therefore \\ (V^A - V^V + \frac{j * n}{mass^A} + \frac{j * n}{mass^B}) * n + e * (V^B - V^A) \cdot n = 0 \] If you recall, the original goal was to isolate our magnitude. This is because we know what direction to resolve the collision in (assumed given by the collision detection), and only have left to solve the magnitude of this direction. The magnitude which is an unknown in our case is \(j\); we must isolate \(j\) and solve for it. <br />
<div align="center"><i>Equation 10</i></div>\[ (V^B - V^A) \cdot n + j * (\frac{j * n}{mass^A} + \frac{j * n}{mass^B}) * n + e * (V^B - V^A) \cdot n = 0 \\ \therefore \\ (1 + e)((V^B - V^A) \cdot n) + j * (\frac{j * n}{mass^A} + \frac{j * n}{mass^B}) * n = 0 \\ \therefore \\ j = \frac{-(1 + e)((V^B - V^A) \cdot n)}{\frac{1}{mass^A} + \frac{1}{mass^B}} \] Whew! That was a fair bit of math! It is all over for now though. It’s important to notice that in the final version of Equation 10 we have \(j\) on the left (our magnitude) and everything on the right is all known. This means we can write a few lines of code to solve for our impulse scalar \(j\). And boy is the code a lot more readable than mathematical notation! <br />
<pre>void ResolveCollision( Object A, Object B )
{
// Calculate relative velocity
Vec2 rv = B.velocity - A.velocity
// Calculate relative velocity in terms of the normal direction
float velAlongNormal = DotProduct( rv, normal )
// Do not resolve if velocities are separating
if(velAlongNormal > 0)
return;
// Calculate restitution
float e = min( A.restitution, B.restitution)
// Calculate impulse scalar
float j = -(1 + e) * velAlongNormal
j /= 1 / A.mass + 1 / B.mass
// Apply impulse
Vec2 impulse = j * normal
A.velocity -= 1 / A.mass * impulse
B.velocity += 1 / B.mass * impulse
}
</pre>There are a few key things to note in the above code sample. The first thing is the check on Line 10, <code>if(VelAlongNormal > 0)</code>. This check is very important; it makes sure that you only resolve a collision if the objects are moving towards each other. <img alt="Two objects collide, but velocity will separate them next frame. Do not resolve this type of collision." height="400" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/randy-gaul/custom-physics-separating-velocities.png" width="600" /> Two objects collide, but velocity will separate them next frame. Do not resolve this type of collision. If objects are moving away from one another we want to do nothing. This will prevent objects that shouldn’t actually be considered colliding from resolving away from one another. This is important for creating a simulation that follows human intuition on what should happen during object interaction. The second thing to note is that inverse mass is computed multiple times for no reason. It is best to just store your inverse mass within each object and pre-compute it one time: <br />
<pre>A.inv_mass = 1 / A.mass
</pre>Many physics engines do not actually store raw mass. Physics engines often times store inverse mass and inverse mass alone. It just so happens that most math involving mass is in the form of <code>1/mass</code>.The last thing to note is that we intelligently distribute our impulse scalar \(j\) over the two objects. We want small objects to bounce off of big objects with a large portion of \(j\), and the big objects to have their velocities modified by a very small portion of \(j\). In order to do this you could do: <br />
<pre>float mass_sum = A.mass + B.mass
float ratio = A.mass / mass_sum
A.velocity -= ratio * impulse
ratio = B.mass / mass_sum
B.velocity += ratio * impulse
</pre>It is important to realize that the above code is equivalent to the <code>ResolveCollision()</code> sample function from before. Like stated before, inverse masses are quite useful in a physics engine. <br />
<h3>Sinking Objects</h3>[...] <a href="http://gamedev.tutsplus.com/tutorials/implementation/create-custom-2d-physics-engine-aabb-circle-impulse-resolution/" target="_blank">Read more: How to Create a Custom 2D Physics Engine: The Basics and Impulse Resolution</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-80571744408943332782013-03-30T07:38:00.001-07:002013-03-30T07:38:57.171-07:00Postmortem: Building Hard-shell Hockey with NME<img alt="NME postmortem" height="380" src="http://blog.allanbishop.com/wp-content/uploads/2013/03/NME-analysis.png" title="Hard-shell hockey" width="640" /><br />
After finally creating my<a href="http://blog.allanbishop.com/hard_shell_hockey_released/"> first game</a> with <a href="http://www.nme.io/">NME </a>and publishing it to the Android store, I thought I would share my experience so far.<br />
<br />
To begin, I should explain what NME is and what it can do since I have only given it a brief mention before.<br />
According to the official site NME is:<br />
<blockquote>“The best way to build cross-platform 2D games or rich applications.”<br />
<span style="color: black;">“Using the innovative Haxe language compiler, NME deploys the same source code to C++, JavaScript and SWF bytecode without sacrificing reliability. As a result, NME provides fast hardware-accelerated performance for Windows, Mac, Linux, iOS, Android and BlackBerry, while also supporting Flash Player and HTML5. NME mirrors the traditional Flash API, so developers can leverage their existing experience to target new platforms, with better results.”</span></blockquote>So far I have to say that statement is pretty accurate. But what about other similar tools that exist such as Corona, Unity, libGDX, Marmalade etc and why did I choose NME over them?<br />
One of the more obvious reasons why I chose NME was my past experience with the Flash API which certainly lowered the learning curve. However, it was the fact that NME is the only truly free solution that won me over. LibGDX came closest out of the other choices I mentioned but it still required a $400 license fee for iOS. Having witnessed the HTML5 vs. Flash war I feel it is much safer to bet on technologies that are free and open source.<br />
Of course NME is not without its flaws. Bugs and issues with various platforms do exist although fortunately they are few and far between. Additionally the community is not huge and so one can’t expect the same level of documentation and tutorials. That being said, I have really noticed over the past year how polished NME is becoming and how the community is growing which is fantastic to see. I am very much looking forward to seeing shader support for mobiles being added too.<br />
So, having decided upon NME as the tool to use I realised I needed a game engine. When I first started there was not much choice so I decided to port over an engine I had made in Flash. As of now, ports of the popular Flash game engines like HaxeFlixel and HaxePunk exist. Regardless, software architecture and game engine design has interested me so I don’t feel that I wasted my time by creating my own and so far am very pleased with my results.<br />
That being said, I did greatly underestimate how much work was involved in getting the game engine working properly.<br />
The first challenge was getting the hang of rendering in a different way to what I had been accustomed to with Flash. In Flash, I would mainly use the DisplayList and at times blitting. This works great in web browsers but less so on mobile devices. Blitting actually causes the mobile to render via software which kills performance. The DisplayList, whilst better (it is GPU accelerated), is still not the optimum way of rendering. The best way when considering performance on mobiles is drawTiles and drawTriangles respectively. This means using a third party tool to export a swf into a tilesheet to render via drawTiles.<br />
After understanding and implementing drawTiles, my next problem was displaying Android ads. I managed to find a library that used NME extensions to achieve this except that it did not work out of the box. Eventually I tracked down another person who had managed to get it up and running and they gave me a lot of tips. In the end this required delving into some of the NME framework and modifying the Java code template. It was after this that I decided to just focus on developing for Android as I did not want to waste a similar amount of time getting iOS ads working (although I believe they work out of the box on that platform) [...]<br />
<br />
<a href="http://blog.allanbishop.com/postmortem-building-hard-shell-hockey-with-nme/" target="_blank">Read more: Postmortem: Building Hard-shell Hockey with NME</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-89373370098915743542013-03-22T11:14:00.001-07:002013-03-22T11:14:56.249-07:00From Zero to Pitch: A Walkthrough for Game DesignersHow can you take a rough game idea and turn it into something fun, interesting and engaging? This is definitely one of the most difficult obstacles that you must tackle as a game designer, as your job is to craft enjoyable experiences in a constrained environment. Would you believe me if I told you that after you finish reading and participating in the activities established in this article, you will have a game designed and ready to be developed? Yes, I know it sounds inconceivable, but trust me – this series of unconventional exercises will explain the workflow of designing a brand new game from zero to pitch. <br />
<hr /><h2>Strengthen Your Game Design Muscle</h2>I want to share with you one of the habits that helps me strengthen my game design muscle all the time:s turning real life experiences into games. When I started developing video games, I acquired the habit of trying to take everyday experiences and imagine them in terms of a video game; this makes you very aware of the things that are happening around you and the fun or frustrating factors in them. For example, let’s say that you took a flight and when you arrived at the airport your luggage got lost. This is a very frustrating scenario, but now take that experience and try to imagine how did the luggage got lost and what are the persons involved in that particular situation. Could you make a game based on this? <br />
<div><img alt="Can you take something apparently dull and turn it into something fun?" height="450" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_airport.jpg" width="600" /> Can you take something apparently dull and turn it into something fun?</div>What about a game where the player has to manage the conveyor belts at an airport and he loses points when passengers reach a certain amount of frustration levels when they don’t get their luggage? Or what if you experienced some turbulence during your flight and you got a little bit nervous… could you make a game where you had to fly an airplane and gain points by doing abrupt manoeuvres and scaring the passengers? Of course you can! This is the raw idea that you need to write down on paper and start working on. As a matter of fact, there’s this little booklet called the <a href="http://tinygdtool.urustar.net/">Tiny Game Design Tool</a> that can make this process a little bit easier, by helping you jot the idea down as soon as possible. This tool is basically a printable PDF that you can carry in your wallet which helps you establish in very little time the following basic elements of your game: <br />
<ul><li>Emotion, Mechanic and Theme</li>
<li>Main Character</li>
<li>Objects</li>
<li>Obstacles</li>
<li>Level Design</li>
</ul><hr /><h2>Play With the Elements</h2><div><img alt="The alchemy of creativity (Image taken from Everything is a Remix Part 3)" height="337" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_elements.jpg" width="600" /> The alchemy of creativity. (Image taken from <a href="http://www.everythingisaremix.info/everything-is-a-remix-part-3/">Everything is a Remix Part 3</a>.)</div>We have a raw idea. This idea is like clay: you can mold it, split it into two, make a shape with it, and so on. Now we have to play with this idea… but how? Well, another creative exercise that is very useful to constantly work your game design muscle is to put in good practice the three basic elements of creativity: <i>copy</i>, <i>transform</i> and <i>combine</i>. I took this elements from the third episode of Kirby Ferguson’s documentary <a href="http://www.everythingisaremix.info/watch-the-series/">Everything is a Remix</a> and they will help us exercise our mind so that it can always be wide open to creativity. <br />
<h3>Copy</h3><div><img alt="006_copy" height="129" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_copy.jpg" width="196" /></div>Get practice and experience by copying existing games, but also apply small modifications to make the game easier or more difficult. This process of repetition and modification is called <i>iteration</i> and is very common in software and video game development. An example of some games that follow this exercise are: <br />
<ul><li><a href="http://youtu.be/NDjseVmruH8">Plasma Pong</a>, which is a Pong variant with fluid dynamics and a new game mechanic that lets the ball stick to your paddle.</li>
<li><a href="http://www.kongregate.com/games/briderider/fps-man">FPS-MAN</a>, which is a take on Pac-Man but with a change in perspective. Now you look at the action from the point of view of Pac-Man and it changes the game experience completely.</li>
<li><a href="http://portal.wecreatestuff.com/portal.php">Portal: The Flash Version</a>, which takes the basic mechanics of Portal but constrains them to a two-dimensional space. This is also known as a <a href="http://tvtropes.org/pmwiki/pmwiki.php/Main/VideoGameDemake">demake</a>.</li>
</ul><h3>Transform</h3><div><img alt="006_transform" height="128" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_transform.jpg" width="207" /></div>Did you have an interesting experience today, this week or this month? If you didn’t… borrow one! Take a newspaper and watch the front page news; you will notice that these stories are generally based on events that have something interesting to tell. Pick a story you like and turn it into a video game. Ask yourself questions: Who are the people involved? Where did the action happen? Could the personalities involved be interesting characters for my game? A recent game that tackles this type of exercise is <a href="http://www.indiegogo.com/projects/riot--4?c=home">Riot</a>, in which the player experiences both sides of a protest, as rioters and as police officers. This idea came to fruition when Leonard Menchiari wanted to capture the feeling of his own experience of protests. <br />
<div><img alt="A kid that has to reach an airplane while avoiding security guards, cameras and checkpoints" height="581" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_kid_airport.jpg" width="466" /> A kid that has to reach an airplane while avoiding security guards, cameras and checkpoints.</div>A more personal experience I had with this exercise was a small game I made for a jam where participants had to develop games based on TV news. My game was called “Escape from el Dorado”, and was based on a TV report about a kid that infiltrated the “El Dorado” airport in Bogotá and got into a plane that ended up in Chile. This story made me think immediately about how I could implement stealth mechanics in an airport setting. <br />
<h3>Combine</h3><div><img alt="006_combine" height="137" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_combine.jpg" width="207" /></div>Take an existing game and combine it with another game, or change its genre. What would happen? What if I took a game like Super Mario Bros. and applied a skill tree just like the ones found in Role Playing Games? A recent example of combination is <a href="http://bombermine.com/">Bombermine</a>, which takes the classic Bomberman game and mixes it with multiplayer elements. <br />
<hr /><h2>Planting the Characters’ Seeds</h2>Now that we went from a raw idea to something that is starting to take shape, and slowly but steadily we are covering the basics. Now let’s design the characters. First we’re going to start with a game design tool called <a href="http://www.gameseeds.net/">Game Seeds</a>. This game is generally played in groups but for this particular exercise we will play a single player variant focused on character development. <b>Tip:</b>I assume that by now you know the basics of playing <a href="http://www.gameseeds.net/">Game Seeds</a>. If not, please take a couple of minutes to <a href="http://gamedev.tutsplus.com/articles/game-design-articles/planting-a-game-idea-with-game-seeds/">read my guide here</a>. <br />
<div><a href="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/michael-james-williams/game_seeds_cards1.jpg"><img alt="Click here to see the full size image" height="468" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_card_set.jpg" width="600" /></a> Click to see the <a href="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/michael-james-williams/game_seeds_cards1.jpg">full size image</a>.</div>We’re going to start with this fifteen card grid as our foundation. Please pick just <i>six cards</i> that have game mechanics that appeal to you. Now, in three steps we’re going to fill the Game Seeds sheet found below with the information given to us by the cards: <br />
<div><a href="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/michael-james-williams/game_seeds_sheet_template.jpg"><img alt="This is the Game Seeds sheet. Click here to download the printable version" height="588" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_game_seeds_sheet_ENG_small.jpg" width="600" /></a> This is the <a href="http://www.gameseeds.net/">Game Seeds</a> sheet. Click to download the <a href="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/michael-james-williams/game_seeds_sheet_template.jpg">printable version</a>.</div><hr /><h2>Step 1: Fill the Hero Profile</h2><div><img alt="006_seeds" height="250" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_seeds.jpg" width="600" /></div>Now that you have selected the six cards, go through each one and write down the icons that appear the most for each category. (In the case of a draw, choose the one you like the most.) For example, in the “species” category of your six cards you might have three human icons, two robot icons and one creature icon; based on this your character will be human. <br />
<h3>Example</h3>From the fifteen card grid I chose Fight, Escape, Race, Duel, Destroy and Navigate. Using those cards this was my character: <br />
<ul><li><b>Creature</b> (3 occurrences) or <b>Robot</b> (3 occurrences) (a draw, therefore I pick <b>Robot</b>)</li>
<li><b>Androgyne</b> (4 occurrences)</li>
<li>Lives in the <b>past</b> (4 occurrences)</li>
<li><b>Nomad</b> (5 occurrences)</li>
<li><b>Tall</b> (3 occurrences) or <b>Short</b> (3 occurrences) (a draw, therefore I pick Tall) and <b>Heavy</b> (4 occurrences)</li>
</ul><hr /><h2>Step 2: Fill the Hero Attributes</h2>Now take a look at the bottom of the cards and mark the Hero Attributes section with an “X” for each attribute that appears. <br />
<h3>Example</h3>Using the cards I chose I get the following attributes: <br />
<ul><li><b>STR</b> (STRENGTH) (6)</li>
<li><b>HEA</b> (HEALTH) (6)</li>
<li><b>DEX</b> (DEXTERITY) (4)</li>
<li><b>WIS</b> (WISDOM) (2)</li>
<li><b>CHAR</b> (CHARISMA) (0)</li>
</ul>So Strength and Health are the main attributes of my character, and it is neither wise nor charming! Once you’ve done this, add your personal touch to the character in the Character Development section. This will define all the details that are going to give personality to your character. <br />
<hr /><h2>Step 3: Pick the Mechanic; Draw Your Hero</h2>Finally, pick your favourite game mechanic from the six cards you chose. This will be your main gameplay mechanic. Now you can draw a sketch of your hero based on all the attributes and his profile. This is my hero sketch, a tall and heavy androgyne robot in a steampunk world who was built using parts from a bank vault: <br />
<div><img alt="This is the point were you realize I suck at drawing" height="564" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_robot.jpg" width="420" /> This is the point were you realize I suck at drawing.</div><hr /><h2>The Basic Elements of Game Design</h2><div><img alt="006_4_elements" height="300" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_4_elements.jpg" width="600" /></div>Now that we have a basic foundation of our game and a main character, it’s time to play with the elements that will form the game. I recommend you start with the elemental tetrad shown above because it’s going to be very straightforward for you when defining your game and the experience you want to give to your players. Use what you have done so far as a guide to define the following: <br />
<ul><li><b>Aesthetics:</b> This is how the game looks, sounds and feels, and it’s also what has the most direct relationship to the player.</li>
<div><img alt="Limbo is a game that is very good at capturing someone's attention just by it's aesthetics" height="236" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_limbo.jpg" width="420" /> <a href="http://limbogame.org/">Limbo</a> is very good at capturing someone’s attention just by its aesthetics.</div><li><b>Mechanics:</b> These are the rules of your game. Use the game mechanic you chose in the previous activity and expand on it, asking yourself what the main goal of your game is and how players are going to achieve it.</li>
<div><img alt="Pong is a game that has a very limited set of rules, but that doesn't mean the game will be boring" height="252" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_pong.jpg" width="420" /> Pong has a very limited set of rules, but that doesn’t mean it’s boring.</div><li><b>Story:</b> What tale do you want to tell through your game? Is it going to be a micro-narrative as in <a href="http://gamedev.tutsplus.com/articles/game-design-articles/nintendo-hard-why-old-games-were-so-difficult/">NES games</a>, or is it going to be a complex and branching story?</li>
<div><img alt="David Cage is always pushing the envelop in terms of storytelling with games like Indigo Prophecy and Heavy Rain" height="225" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_indigo.jpg" width="420" /> David Cage always <a href="http://gamedev.tutsplus.com/articles/game-design-articles/how-heavy-rains-narrative-is-strengthened-by-its-gameplay/">pushes the envelope in terms of storytelling</a>, with games like Indigo Prophecy and Heavy Rain.</div><li><b>Technology:</b> This is the medium in which the aesthetics, mechanics and story will take place. What kind of technology are you going to use that will make the game possible?</li>
<div><img alt="Maybe your game works better as a board game, or as a game for smartphones" height="197" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/david-arcila/006_board.jpg" width="420" /> Maybe your game works better as a board game, or as a game for smartphones.</div></ul><hr /><h2>Look at Your Creation Through Lenses</h2>Our game is growing and finally taking shape, and now it’s time to polish the rough corners. To do this we are going to use the questions from the <a href="http://gamedev.tutsplus.com/articles/game-design-articles/testing-every-aspect-of-your-game-design-with-a-deck-of-lenses/">Deck of Lenses</a> and focus them in areas of our game that we think need improvement. <br />
<a href="http://gamedev.tutsplus.com/tutorials/game-design/from-zero-to-pitch-a-walkthrough-for-game-designers/" target="_blank">Read more: From Zero to Pitch: A Walkthrough for Game Designers</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-24059152356241111012013-03-12T16:47:00.001-07:002013-03-12T16:49:00.178-07:00How to Speed Up A* Pathfinding With the Jump Point Search AlgorithmPathfinding is ubiquitous in games. So it’s important to understand the implications which are present when using algorithms such as A*. In this tutorial we’re going to cover a relatively new method for searching grid based worlds: <i>Jump Point Search</i>, which can speed up A* by orders of magnitude. <i><b>Note:</b> Although this tutorial is written using AS3 and Flash, you should be able to use the same techniques and concepts in almost any game development environment.</i> <i>This implementation is based on the original paper and article on JPS found here: <a href="http://harablog.wordpress.com/2011/09/07/jump-point-search/">Jump Point Search</a>. The Lua based implementation, <a href="https://github.com/Yonaba/Jumper">Jumper</a>, was used for help with some parts of the implementation.</i> <br />
<hr /><h2>Jump Point Search Demo</h2><div></div>Click the SWF to give it focus, then move your mouse over non-blocking areas of the map to have the NPCs try to get to it. Hit Space to switch between A*, Jump Point Search, and both. No Flash? Check out the YouTube video instead: <br />
<div><iframe frameborder="0" height="450" src="http://www.youtube.com/embed/jCZw2mBjrBI" width="600"></iframe></div><hr /><h2>Setup</h2>The demo implementation above uses AS3 and Flash with the <a href="http://gamua.com/starling/">Starling Framework</a> for GPU accelerated rendering and the <a href="https://github.com/polygonal/ds">polygonal-ds</a> library for data structures. <br />
<hr /><h2>Pathfinding</h2>Pathfinding is often used in video games and you are sure to bump into it at some point during your game development career. Its primary use is to give intelligent looking movement behavior to artificial entities (NPCs), to avoid them bumping into things (often). In some games the player avatar is also subject to pathfinding (strategy games, many third person RPGs and adventure games). So you might assume that the problem of pathfinding is solved, but unfortunately that’s not the case; there is no silver bullet which you can use and just be done with it. And even in big AAA games, you will still find funny things like this: <br />
<div><iframe frameborder="0" height="338" src="http://www.youtube.com/embed/TYlWFbCknAI" width="600"></iframe></div>There may not be a silver bullet, but there is a bullet: the A* (A star) algorithm. In this tutorial we are going to see a brief overview of A* and how to speed it up using another algorithm, Jump Point Search. First we need a way to represent our game world in a way that a pathfinding algorithm can use it. <br />
<hr /><h2>World Representations</h2>One of the most important things to consider when thinking about pathfinding for your game is <i>world representation</i>. How is the data of the passable areas and obstacles organized with programming structures in memory? The simplest representation you can use is a grid-based structure, where path nodes are organized in a grid and can be represented by a 2D array. We are going to use this representation in this tutorial. Specifically it will be an eight-way grid representation: allowing movement in straight and diagonal directions. <br />
<div><img src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/tomislav-podhraski/GridMap.png" /> The black pixels in the image represent the blocking cells.</div>Your requirements might be different, so this structure might not suit you. Good thing is that with some processing (usually done offline) you can change pathfinding representations to other formats. Alternatives to grid based approach would include things like polygon (obstacles represented by polygons) or navigation meshes (navigation areas represented by polygons); these can represent the same data with fewer nodes. Another data that can be stored in map representation are <i>costs</i>: how much it costs to travel from one node to another. This can be used for the AI to determine the path that, for example, prefers roads over regular terrain (making the cost of the road less than the terrain). Jump Point Search is specifically designed for eight-way grid based map representation so we’ll use that. Also, in its vanilla form it doesn’t support weighted maps. (In the final section I’ll discuss a possible way to remedy this.) <br />
<hr /><h2>A* Pathfinding Refresher</h2>Now we have a world representation let’s take a quick look at implementing A*. It’s a weighted graph search algorithm which uses heuristics (little “hints”) of how to best search the area from the start node to the end node. I highly recommend that you check out this visualization of pathfinding algorithms: <a href="http://qiao.github.com/PathFinding.js/visual/">PathFinding.js – visual</a>. Playing with it can boost your intuition of what the algorithm is actually doing – plus it’s fun! For pathfinding using A* in rectangular grids we do the following: <br />
<pre>1. Find node closest to your position and declare it start node and put it on
the open list.
2. While there are nodes in the open list:
3. Pick the node from the open list having the smallest F score. Put it on
the closed list (you don't want to consider it again).
4. For each neighbor (adjacent cell) which isn't in the closed list:
5. Set its parent to current node.
6. Calculate G score (distance from starting node to this neighbor) and
add it to the open list
7. Calculate F score by adding heuristics to the G value.
</pre><br />
<li><a href="http://www.policyalmanac.org/games/aStarTutorial.htm">A* Pathfinding for Beginners</a> (In-depth article that explains F and G scores among other things.)</li><br />
Heuristics is essentially making a guess at the chance that the node being evaluated will lead to the goal. Heuristics can make a big difference in efficiency of pathfinding algorithms as they tend to limit the number of nodes that need to be visited. We are going to use <a href="http://en.wikipedia.org/wiki/Manhattan_distance">Manhattan distance</a> for our purposes (meaning that nodes closer to the goal will have a smaller number): <br />
<pre>private function manhattanDistance(start:Node, end:Node):int {
return Math.abs(end.x - start.x) + Math.abs(end.y - start.y);
}
</pre>This is more or less it. We stop the algorithm when we find the goal node, and then track back using parent variable of node to construct the path. Search algorithms can be used for other things as well. A* is a general weighted graph search algorithm, and can be used on any such graph. This can cover other fields in AI, such as finding the optimal steps to achieve certain objective: throw a bomb or run for shelter and try to sneak behind an enemy? In game development we need to do things fast, when updating our games at 60 frames per second every millisecond counts. Even though A* performs reasonably well for some uses there exists the need to make it faster or use less memory. <br />
<hr /><h2>Optimizations</h2>Choosing the representation is the first thing that will have an impact on pathfinding performance and your choice of pathfinding algorithm. The size of the graph that is being searched will have a big correlation on how your pathfinding performs (which makes sense; it’s easier to find your way in your room than in a big city). Then you would consider higher level optimizations which usually involve clustering data to smaller regions and then searching those while later refining paths in travelled smaller regions. For example, if you want to go to a restaurant in a neighboring city, you first consider how you get from your city to that one, and once you are in that city you limit your “searching” to the area where the restaurant is located, ignoring the rest. This would include things like <a href="http://leibniz.cs.huji.ac.il/tr/1188.pdf">swamps</a>, <a href="http://www.ru.is/faculty/yngvi/pdf/BjornssonH06.pdf">dead end elimination</a> and <a href="http://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf">HPA*</a>. On the lowest level you have to do the searching. You chose your data representation and possible abstractions and then plug them in an algorithm that will pick out nodes, travel here and there searching for the goal. These algorithms are usually based on the A* searching algorithm with possible modifications. In simpler cases you can get away with using straight A* which offers you the simplicity. I’ve provided a grid based implementation in the <a href="http://source.tutsplus.com/gamedev/authors/TomislavPodhraski/JPS/Demo.zip">source download</a>. <br />
<hr /><h2>Jump Point Search</h2>[...] <a href="http://gamedev.tutsplus.com/tutorials/implementation/speed-up-a-star-pathfinding-with-the-jump-point-search-algorithm/" target="_blank">Read more: How to Speed Up A* Pathfinding With the Jump Point Search Algorithm</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-66421746559416382922013-02-28T12:32:00.001-08:002013-02-28T12:33:06.168-08:00Making it in Indie Games: Starter Guide<img alt="image" src="http://derekyu.com/tumblr/imindie.jpg" /> Every now and then someone will ask me for advice on making it as a professional indie game developer. First, it’s a huge honor to be asked that. So I want to say “Thank you!” Second… damn, if I really want to help out it’s a serious endeavor. Of course, I could always say <i>“Give it your best! Work hard! Be true to yourself!”</i> and it wouldn’t be a terrible reply… just not a terribly useful one, either. So here it is. Here is what I’m going to link when that rare situation arises again, because it’s too much work to write it up more than once! This is advice that I feel may actually be practical to someone who is just starting out as an indie game developer. Hope it helps! <b>INDIEPENDENT</b> So yeah, what does being “indie” even mean? Is “indie” short for independent? Is this game “indie”? Is “indie” a genre? IT’S CONFUSING - WHY DO WE NEED THE WORD “INDIE” AT ALL. To answer the last question, I offer the following scenarios. Scenario 1: a person is looking to make games, and perhaps start their own studio. They type “game development” into a search engine. The results, to say the least, are underwhelming. Dry. Academic. Programming-centric. (Try it yourself and see.) Scenario 2: the person instead types “indie games” into a search engine. Instead of pages upon pages of conferences, bachelor’s degrees, and programming tools, that person is met instead with pages upon pages of games to play and vibrant communities filled with people who are doing exactly what he or she wants to be doing. Some of them went to school, but many did not. A wealth of different ideas and tools are used. There are even documentaries about making games! It’s not just something where you get a degree and wait in line for a job. You can start making games RIGHT NOW. The word “indie” is more than just a way to describe a type of developmental process… like any label, it actually provides an avenue for people to explore that process and then flourish within it. It has a real purpose. It serves real lessons on game creation and entrepreneurialism. It offers real motivation! Of course, it can be irritating to see the term misused, or become a vehicle for pretentiousness and arrogance. Like any label, “indie” also breeds a certain amount dogmatism, croneyism, and other -isms. But the net result is really worth something. As someone who once gave up on professional game-making because I thought it meant a 9-to-5, I can tell you that it’s genuinely valuable. As for what games are “truly” indie, we’ll never fully agree, and that’s probably for the best. But I can tell you the criteria I’ve devised for <a href="http://www.tigsource.com/">The Independent Gaming Source</a> to determine whether a game is fit for coverage: <b>1.</b> “Independent”, as in no publisher. <b>2.</b> Small studio (roughly 20 members or less). I choose that definition because it’s the most useful one. Someone who is looking to become an “indie” game developer is interested in what is possible under those constraints and how those types of studios operate. It excludes companies like Valve and Double Fine, which are certainly independent but too large to be “indie”. It also excludes “feels indie”-type games that are not self-published. Under that definition you still run into gray areas, but hey, just because we don’t know when “red” turns into “purple” doesn’t mean the words aren’t useful. Just think about someone who wants to make a game with a small team and self-publish it… what should they type into Google for inspiration, advice, community, etc.? “Indie” is still as good a word as any, in my opinion. <b>So, should I go to school to learn how to make games?</b> The most important thing to know about video game development and schooling is that no one, whether it’s an indie studio or big company, cares about degrees. How could it, when some of its most prominent members are drop-outs or never-beens? John Carmack, Cliff Bleszinski, Jonathan Blow, and Team Meat are all prominent members of this club. A degree is a piece of paper that says you can do something in theory - game developers want to know that you have enough passion to do real work, regardless of whether you’re being graded on it. And if you’re thinking of going indie, it won’t matter what other people think - you’ll simply need that passion to succeed or else you won’t. You’re the only one holding the door open in that case. This isn’t to dissuade you from going to college, per se (I studied computer science in college, and while it was far from a perfect experience, I also gained a lot from both the curriculum and the friends I made there). The point is <i>make something</i> - games, mods, art, and music. If school helps you with that, great. If it doesn’t, then you need to rethink how you’re spending your most valuable resources: time and money (both of which can be exorbitant costs for schooling). <b>If I go to school, what should I study?</b> At a <i>regular university</i>, I would suggest majoring in computer science, even if you “just want to be a designer”. The design of games is very much tied to how they are made. At an <i>art school</i>, illustration, concept art, and 3d modeling courses are probably the most useful for games. At a <i>game school</i>, they will hopefully try to involve you in all aspects of game creation, from programming to design. I would stay far away from design-only schools or curricula - those are either scams or are better suited to academia than actual game-making. Also, it’s worth finding out whether or not the school owns what you make while you’re a student there. <i>See also: <a href="http://the-witness.net/news/2011/06/how-to-program-independent-games/">Jonathan Blow - How to Program Independent Games</a> (read the comments as well as watch the video)</i> <b>Okay, you say make something. How do I start?</b> My best advice for those starting out is not to get ahead of themselves. It’s easy to start worrying about tools, teams, platforms, deals, marketing, awards, and whatever else before you’ve even gotten a sprite moving around the screen. Those stars in your eyes will blind you. They’ll freeze you up. You need to be actively making games all the time. If we were talking about painting, I’d tell you to pick up a painting kit and a sketchpad at your local art store ASAP and just have at it. You’d proceed to put absolute crap down on the pad and get frustrated. But it’d also be kind of fun - so you’d keep doing it. Along the way you’d read some theory and study other people’s work. With good taste and under a critical eye, you would keep doing that until the day you painted something good. We’re talking about games, though. I recommend <a href="http://www.yoyogames.com/gamemaker/windows">Game Maker</a> and <a href="http://unity3d.com/">Unity</a> as two all-purpose game-making suites. They both have a good balance of power versus ease-of-use; they’re both affordable or have free demos, and they both have a wealth of tutorials and plug-ins online. Both are used by professional developers (Unity in particular). Grab one of those and start running through the tutorials. When you run into trouble, ask for help. Give help back when you begin figuring things out. Get active in a game-making community. But above all else, keep making games. It’s the only way to truly answer all of those questions in your head right now. Also, watch this: <b>LASTLY, MY TOP 10 TIPS</b> <br />
<a href="http://makegames.tumblr.com/post/44181247500" target="_blank">Read more: Making it in Indie Games: Starter Guide</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-23269685887008236392013-02-11T08:13:00.001-08:002013-02-11T08:14:45.095-08:00Creating Sprite Sheets in Five Minutes With Texture PackerSo you’ve started working on your project, you got the basics down and now you are at the part where you actually want to implement some graphics… but you’re not quite sure how to do that. Let me introduce you to <a href="http://www.codeandweb.com/texturepacker">Texture Packer</a>.<br />
<hr /><h2>What Is Texture Packer?</h2>Created by the guys over at <a href="http://www.codeandweb.com/">Code n’ Web</a>, Texture Packer is a great little piece of software that allows you to pack textures, assets, and pretty much anything you want in a nifty little sheet that is compatible with tons of frameworks!<br />
<a href="http://www.codeandweb.com/texturepacker/download">A free version is available</a>, but some features are disabled.<br />
I love Texture Packer because it’s easy to use, it’s super flexible and it works with the engines you already use. It does an amazing job of letting you optimize your sheets with various options such as color depth, auto scaling, dithering and trimming invisible pixels. It also exports to many formats compatible with Cocos 2D, Unity, Corona, any engine that supports JSON, and more.<br />
<hr /><h2>The Main Interface</h2>Before we start to make our own sheet, let’s look at the interface for a second.<br />
<div><img alt="Texture Packer: Sprite Sheets tool" height="436" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/omar-shehata/Interface1.jpg" width="600" /><br />
The main Texture Packer interface.</div>All the settings on the left might look a bit menacing but don’t worry, they are actually really easy to set up. And even better, you only have to set them <i>once</i>; you can then save them and re-use them later for any other sheet you want to create!<br />
As you can see, the sheet’s settings are on the left, the list with our assets is on the right (which is empty right now), and the sheet preview itself in the center.<br />
<hr /><h2>Let’s Get Started!</h2>The first thing to do is open your folder with your magical art, and drag and drop it into Texture Packer’s assets list.<br />
<div><img alt="Texture Packer: Sprite Sheets tool" height="273" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/omar-shehata/Dragging1.png" width="600" /></div>As you can see, they instantly appear in your sheet. You can click on a specific asset in that list and it will highlight in the sheet. (This works the other way around as well.)<br />
<b>Tip:</b> Right under the preview sheet there are some zoom options; feel free to play with those until the sheet fits nicely on screen for a better preview.<br />
Let’s take a look at the mess of options on the left. There are only three categories you have to worry about:<br />
<ul><li><b>Output settings:</b> These take care of where your sheet will be exported and the compression that’s applied to it.</li>
<li><b>Geometry settings:</b> These take care of the sheet’s size and asset scaling.</li>
<li><b>Layout settings:</b> These are all about assets’ placement in your sheet and overall optimization.</li>
</ul>We’ll go through each of these in turn.<br />
<hr /><h2>Output Settings</h2><h3>Data Format</h3>This is the format for the sheet’s data file containing all the information you need, such as coordinates, dimensions, and rotation.<br />
Currently, the following options are available: Cocos2D, Corona, Sparrow/Starling, LibGDC, JSON, Unity3D, LibGDX, Css, Gideros, CEGUI/OGRE, AndEngine, AppGameKit, Slick2D, Moai, BHive, Xml, BatteryTech SDK , EaseIJS, Kwik2 and plain text.<br />
<h3>Data File</h3>This is the path where the data file will be saved, it’s a good practice to keep it in the same folder as the sheet itself.<br />
<b>Tip:</b> It’s a good idea to set the output folder so the sheet and its data file are exported directly into your engine’s directory.<br />
<h3>Texture Format</h3>From here you select the format of the sheet’s image. PNG is recommended, unless you need something else specific for your project.<br />
<h3>Png Opt. Level, DPI, and Premultiply Alpha</h3>Unless you know what you are doing, leave these settings untouched: Png Opt Level at “none”, DPI at 72 and Premultiply Alpha unchecked.<br />
<h3>Image Format</h3>In other words, <a href="http://en.wikipedia.org/wiki/Color_depth">color depth</a>. It’s indicated to leave this untouched as well; the default RGBA8888 is the highest quality option. In case you are going for a specific look or you highly value the size of your sheets you can choose a lower option such as RGBA4444.<br />
The “A” in those abbreviations stands for “Alpha” (transparency), and you will notice that if you pick an option that says only “RGB” it will have a black background, meaning there is no alpha info there. If you need it, you can create an alpha map by selecting “ALPHA” from that list; this may come in handy in some cases so keep it in mind.<br />
<div><img alt="Texture Packer: Sprite Sheets tool" height="323" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/omar-shehata/Colors.png" width="600" /><br />
The difference between RGBA8888 and RGBA4444 is evident in the colors of the main body, above.</div><h3>Dithering</h3>If you haven’t touched the option from the previous step, dithering will be unavailable, but don’t worry about it. Now, in case you selected a lower option in the previous step, such as RGB444, you may notice that you can see where the color tones match… that’s ugly, so dithering is here to help you by mixing colors using some complex algorithms.<br />
Try out the “FloydSteinberg” or “Atkinson” options and see how they look.<br />
<div><img alt="Texture Packer: Sprite Sheets tool" height="350" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/omar-shehata/Dither.png" width="600" /><br />
The effect of the dither is easiest to see in the shirt’s fabric.</div><h3>Texture File</h3>Just like the “Data File” option, from here you choose the path where the sheet image will be exported.<br />
There is one more setting in the Output category called “Auto SD”. This allows you to automatically export a smaller version of the same sheet you are working on at the same time. This is useful when you work on an iOS app that requires two separate sheets in order to work on both normal and retina displays – Texture Packer has you covered.<br />
<hr /><h2>Geometry Settings</h2><h3>Size</h3>This is the place where you can change the size of the sheet. You can pick a maximum size or a fixed size. There are predefined, recommended values in the drop-down menu (all powers of two), but you can also manually input any values you want.<br />
Unless you are working on a project that requires a specific size for the sheet, I suggest you enable the “Allow free sizes” option. This ensures that the sheet size is big enough to accommodate all the assets without leaving any wasted blank pixels. (Also, keep the “Pack” option on “Best”.)<br />
<h3>Scale</h3>From here you can easily re-size your entire sheet from the drop-down menu (also allowing you to add your own values). Right below the scaling number there is another option for the scaling <i>method</i>. The “smooth” and “fast” options are the most common; “fast” does the scaling without blending any pixel color (this could be used to scale up your pixelated graphics for a retro game), and “smooth” scales everything smoothly (obviously).<br />
[...] <br />
<a href="http://gamedev.tutsplus.com/tutorials/game-art/creating-sprite-sheets-in-five-minutes-with-texture-packer/" target="_blank">Read more: Creating Sprite Sheets in Five Minutes With Texture Packer</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-47141851370033763042013-02-11T07:59:00.001-08:002013-02-11T08:00:21.724-08:00Pixel Art Tutorial<img alt="" src="http://www.derekyu.com/images/extras/lucha-finished.gif" /><b><br />
<i>Note:</i></b><i> This tutorial was created in 2007 for my personal website. Some small tweaks have been made since then, but nothing too significant.</i><br />
<br />
In this 10-step tutorial, I’ll teach you how to create a “sprite”, which is a stand-alone two-dimensional character or object. The term comes from video games, of course.<br />
Creating pixel art is a skill I picked up because I needed graphics for my games. After a lot of practice, I became kinda handy with it, and started to see it more as actual art rather than just a tool. These days, pixel art is quite popular in game development and illustration.<br />
This pixel tutorial was created many years ago to teach people the basic concepts behind pixel art, but I’ve streamlined it a lot since its first incarnation. There are other pixel tutorials around, but I find them to be overly-complicated and too wordy. Pixel art is not a science. You should never have to calculate a vector when doing pixel art.<br />
<br />
<h2>1. TOOLS</h2>One of the nice things about pixel art is that you don’t really need any fancy tools – your computer’s built-in paint program is probably good enough! That said, there are programs made specifically for pixel pushing, like Pro Motion, or, for Mac users, Pixen. Can’t say I’ve actually tried them, but I’ve heard good things. For this tutorial, I’m going to use Photoshop, which is an expensive beast, but it’s good for all kinds of art and it’s numerous features are pretty useful for pixelling.<br />
<img alt="" src="http://www.derekyu.com/images/extras/pixel-tools.jpg" /><br />
<b>USING PHOTOSHOP FOR PIXEL ART</b><br />
When using Photoshop, your main weapon is going to be the pencil tool (shortcut “B”), which is the alternate for the brush tool. The pencil lets you color individual pixels, without any anti-aliasing.<br />
<img alt="" src="http://www.derekyu.com/images/extras/pencil-tool.gif" /><br />
Two other tools that will come in handy are the marquee tool <img alt="" src="http://www.derekyu.com/images/extras/marquee-icon.gif" /> (shortcut “M”) and the magic wand <img alt="" src="http://www.derekyu.com/images/extras/wand-tool.gif" /> (shortcut “W”) for selecting and dragging or copying and pasting. Remember that by holding “Shift” or “Alt” while you make your selection you can add or subtract from your current selection. This comes in handy when trying to grab areas that aren’t perfectly square.<br />
You’ll also use the eyedropper <img alt="" src="http://www.derekyu.com/images/extras/eyedropper-icon.gif" /> (shortcut “I”) to grab colors. Color conservation is important in pixel art for a number of reasons, so you will want to grab the same colors and reuse them.<br />
Finally, make sure you learn the shortcuts. They can save you a lot of time and energy. A good one to know is “X”, which switches your primary and secondary colors.<br />
<h2>2. LINES</h2>Pixels are essentially little blocks of color. The first thing you need to learn is how to use these blocks effectively to make any kind of line that you want. We’ll discuss the two most basic types of lines, straight and curved.<br />
<b>STRAIGHT LINES</b><br />
I know what you’re thinking – this seems too easy to even bother with! But with pixels, even straight lines can be problematic. What we want to avoid are “jaggies” – little breaks in the line that make the line look uneven. Jaggies crop up when one piece of the line is larger or smaller than the surrounding pieces.<br />
<img alt="" src="http://www.derekyu.com/images/extras/straight_jag.gif" /><br />
<b>CURVED LINES</b><br />
For curvature, make sure that the decline or incline is consistent all the way through. In this next example, the clean-looking curve goes 6 > 3 > 2 > 1, whereas the curve with the jaggy goes 3 > 1 < 3.<br />
<img alt="" src="http://www.derekyu.com/images/extras/curved_jag.gif" /><br />
<b>CONCLUSION</b><br />
Being comfortable making any line in pixels is crucial to doing pixel art. Later on, we’ll learn how to use anti-aliasing to make our lines look really smooth.<br />
<h2>3. CONCEPTUALIZING</h2>The first thing you need is a good idea! Try to visualize what you want to pixel, either in your head or on paper. A little work in the pre-planning department can let you concentrate on the actual pixelling.<br />
<b>THINGS TO THINK ABOUT</b><br />
<b>1. What will the sprite be used for?</b> Is this for a website, or a game? Will I have to animate this later, or is this it? If the sprite will be animated later on, you may want to keep it smaller and less detailed. Conversely, you can pack as much detail into a static sprite that you will never have to deal with again. But think about where the sprite is going to go, and what will work best.<br />
<b>2. What constraints are being placed on me?</b> Earlier, I had said that color conservation is important. One of the reasons is that your palette of colors may be limited, either by hardware (less likely these days) or for coherency. Or accuracy, if you are emulating a specific style (C64, NES, etc.) Also, consider the dimensions of your sprite and how it will fit with its surroundings.<br />
<b>LET’S WRASSLE!</b><br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-sketch.jpg" /><br />
For this tutorial, I didn’t really have any constraints, but I wanted to make sure the sprite was large so that you could clearly see what was happening with each step. To that end, I decided to use the Lucha Lawyer, the ass-kickin’est wrestling attorney around, as my model! He could be in a fighting game, or something, with moves like the “Habeus Corpse Blaster”.<br />
<h2>4. THE OUTLINE</h2>A black outline will provide a good, basic structure to your sprite, so it’s the perfect place to start. The reason we choose black is that it’s nice and dark. Later on, I’ll show you how you can change the color of the outline for more realism.<br />
<b>TWO APPROACHES</b><br />
There are two ways to approach the outline. You can draw the outline freehand and then clean it up, or you can start by placing the pixels as you want them from the start. You know, like, “click, click, click”.<br />
I think which approach you should use depends on the size of the sprite and your skill at pixelling. If a sprite is very large, it’s much easier to sketch the outline freehand to get the general shape and then clean it up later than to try and get it right the first time through.<br />
In this tutorial, we’re creating a fairly large sprite, so I’ll demonstrate the first method. It’s also easier to illustrate with text and pictures.<br />
<b>STEP 1: CRUDE OUTLINE</b><br />
Using your mouse or tablet, sketch out a crude outline for your sprite. Make sure it’s not TOO crude, though – it should resemble more or less the final product that you want.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-outline-dirty.gif" /><br />
In this case, I’m basing my outline almost entirely on my sketch.<br />
<b>STEP 2: CLEAN UP THE OUTLINE</b><br />
First, crank up the zoom to around 6x or 8x magnification so that we can see each pixel clearly. Then clean up that outline! In particular, you want to trim away stray pixels (the outline should only be one pixel thick all the way through), get rid of any jaggies, and add any small details that were passed over in Step 1.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-outline-clean.gif" /><br />
Even large sprites never usually exceed 200 by 200 pixels. The phrase “doing more with less” never rings more true than when pixelling. And you will soon find that one pixel can make all the difference.<br />
Keep your outline simple. The details will emerge later on, but for now, concentrate on defining the “big pieces”, like muscle segmentation, for instance. It may not look like much now, but be patient.<br />
<h2>5. COLOR</h2>With the outline done, we have a coloring book of sorts that we can fill in. Paint buckets and other fill tools will make it even easier for us. Picking colors can be a little more difficult, however, and color theory is a topic that is beyond the scope of the tutorial. However, here are a few basic concepts that are good to know.<br />
<b>HSB COLOR MODEL</b><br />
<img alt="" src="http://www.derekyu.com/images/extras/hsb.jpg" /><br />
HSB stands for (H)ue, (S)aturation, and (B)rightness. It’s one of a number of computer color models (i.e. numerical representations of color). Other examples are RGB and CMYK, which you have probably heard of. Most paint programs use HSB for color-picking, so let’s break it down:<br />
<b>Hue</b> – What you understand “color” to be. You know, like “red”, “orange”, “blue”, etc.<br />
<b>Saturation</b> – How intense the color is, or how intense the color is. 100% saturation gives you the brightest color, and as saturation decreases, the color becomes more gray.<br />
<b>Brightness</b> (or “luminosity”) – Lightness of a color. 0% brightness is black.<br />
<b>CHOOSING COLORS</b><br />
What colors you choose is ultimately up to you, but here are a few things to keep in mind:<br />
<b>1.</b> Less saturated and less bright colors tend to look more “earthy” and less cartoony.<br />
<b>2.</b> Think about the color wheel – the further away two colors are from one another, the more they will separate. On the other hand, colors like red and orange, which have close proximity on the color wheel, look good together.<br />
<img alt="" src="http://www.derekyu.com/images/extras/wheel.jpg" /><br />
<b>3.</b> The more colors you use, the more distracted your sprite will look. To make a sprite stand out, use only two or three main colors. (Think about what just red and brown did for Super Mario back in the day!)<br />
<b>APPLYING COLORS</b><br />
The actual application of color is pretty easy. If you’re using Photoshop, you want to first select the area you’re going to fill with the magic wand <img alt="" src="http://www.derekyu.com/images/extras/wand-tool.gif" /> (shortcut “W”) and then fill by pressing “Alt-F” (primary color) or “Ctrl-F” (secondary color).<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-color.gif" /><br />
<h2>6. SHADING</h2>Shading is a crucial step on our quest for pixel demi-god status. Here’s where the sprite either gets some pop, or it devolves into a horrible mess. Heed my words, however, and you’re sure to succeed.<br />
<b>STEP 1: CHOOSING A LIGHT SOURCE</b><br />
First, we have to pick a light source. If your sprite is part of a larger scene, there might be all kinds of local light sources (like lamps, fire, lamps on fire, etc.) shining on it. These can mix in very complex ways on the sprite. For most cases, however, picking a distant light source (like the sun) is a better idea. For games, you will want to create a sprite that is as generally lit as possible so that it can be used anywhere.<br />
I usually choose a distant light source that is somewhere above the sprite and slightly in front of it, so that anything that is on top or in front is well-lit and the rest is shaded. This lighting looks the most natural for a sprite.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lightsource.jpg" /><br />
<b>STEP 2: SHADING</b><br />
Once we have defined a light source, we start shading areas that are farthest from the light source with a darker color. Our “up and to the front” lighting model dictates that the undersides of the head, the arms, the legs, etc., should be shaded.<br />
Remember that the play between light and shadow defines things that are not flat. Crumple up a piece of white paper into a ball and then unroll it and lay it on a table – how can you tell that it’s not flat anymore? It’s because you can see the little shadows around the crinkles. Use shading to bring out the folds in clothing, and to define musculature, hair, fur, cracks, etc.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-shade01.gif" /><br />
<b>STEP 3: SOFT SHADOWS</b><br />
A second shade, lighter than the first, should be used for soft shadows. These are areas that are indirectly lit. It can also be used to transition from the dark to the light, especially on curved surfaces.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-shade02.gif" /><br />
<b>STEP 4: HIGHLIGHTS</b><br />
Places that are being hit directly by the light source can have highlights applied onto them. Highlights should be used in moderation (much less than shadows), because they are distracting.<br />
Always apply highlights after shadows, and you will save yourself some headache. Without the shadows already in place, you will be inclined to make the highlights too large.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-shade03.gif" /><br />
<b>DO’S AND DON’T’S</b><br />
Shading is where most beginners get tripped up. Here are some rules you should always follow when shading:<br />
<b>1. Don’t use gradients.</b> The ultimate newb shading mistake. Gradients look dreadful, and don’t even begin to approximate the way light really plays off a surface.<br />
<b>2. Don’t use “pillow-shading”.</b> Pillow shading is when one shades from the outline inward. It’s called “pillow-shading” because it looks pillowy and undefined.<br />
<b>3. Don’t use too many shades.</b> It’s easy to think that “more colors equals more realistic”. In the real world, however, we tend to see things in big patches of light and dark – our brains filter out everything in between. Use at most two shades of dark (dark and really dark), and two shades of light (light and really light) on top of your foundation color.<br />
<b>4. Don’t use colors that are too similar.</b> There’s no reason to use two colors that are very similar to one another. Unless you want really blurry-looking sprites!<br />
<h2>7. DITHERING</h2>Color conservation is something that pixel artists have to worry about a lot. One way to get more shades without using more colors is to use a technique called “dithering”. Similar to “cross-hatching” or “stippling” in the traditional art world, you take two colors and interlace them to get, for all intents and purposes, an average of the two colors.<br />
<b>SIMPLE EXAMPLE</b><br />
Here’s a simple example of using two colors to create four different shades using dithering:<br />
<img alt="" src="http://www.derekyu.com/images/extras/dither01.gif" /><br />
<b>ADVANCED EXAMPLE</b><br />
<img alt="" src="http://www.derekyu.com/images/extras/dither02.jpg" /><br />
Compare the top picture, which was made using the Photoshop gradient tool, and the bottom, which was created with just three colors using dithering. Notice the different patterns that were used to create the intermediary colors. Try experimenting with different patterns to create new textures.<br />
<b>APPLICATION</b><br />
Dithering can give your sprite that nice retro feel, since a lot of old video games relied heavily on dithering to get the most out of their limited palettes (look to the Sega Genesis for lots of examples of dithering). It’s not something that I use very often, but for learning’s sake, here it is applied (possibly over-applied) to our sprite.<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-dither.gif" /><br />
You can use dithering as much or as little as you want. Honestly, it’s a technique that I’ve only seen a few people use really well.<br />
<h2>8. SELECTIVE OUTLINING</h2>Selective outlining, or “selout”, is kind of like shading the outline. Rather than using black all the way around, we apply a color that is closer to the color of the sprite itself. Also, we vary the brightness of this outline along the edge of the sprite, letting the light source dictate which colors we apply.<br />
Up until this point, we’ve kept the outline black. And there’s nothing wrong with that, really, since it looks pretty good and it keeps the sprite well-separated from its surroundings. But by using black, we are sacrificing more realism than we might like to, since it gives the sprite a “cartoony” look. Selout is a great way to get around that:<br />
<img alt="" src="http://www.derekyu.com/images/extras/lucha-selout.gif" /><br />
You’ll notice I also used selout to soften the folds of his muscles. Finally, the sprite begins to look like a coherent whole rather than a whole bunch of separate pieces.<br />
[...] <br />
<a href="http://makegames.tumblr.com/post/42648699708" target="_blank">Read more: Pixel Art Tutorial</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-92038507250857636252013-01-21T12:06:00.001-08:002013-01-21T12:06:47.069-08:00The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and SeparationIn the natural world, organisms exhibit certain behaviors when traveling in groups. This phenomenon, also known as <i>flocking</i>, occurs at both microscopic scales (bacteria) and macroscopic scales (fish). Using computers, these patterns can be simulated by creating simple rules and combining them. This is known as <i>emergent behavior</i>, and can be used in games to simulate chaotic or life-like group movement. <i><b>Note:</b> Although this tutorial is written using Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.</i> <br />
<hr /><h2>Introduction</h2>In this tutorial, I will cover the three main rules used to simulate flocking and explain how to implement each one. Before we begin, here’s some terminology I’ll be using: <br />
<ul><li><b>Agent</b>: A single entity or character.</li>
<li><b>Velocity vector</b>: An agent’s current velocity.</li>
<li><b>Neighborhood</b>: A certain area around the agent, used to look for other agents.</li>
<li><b>Resultant</b>: The vector obtained from the calculations of the rule.</li>
</ul>This demo shows the effects of the three flocking rules which I’ll explain in this tutorial: <i>alignment</i>, <i>cohesion</i>, and <i>separation</i>. <br />
<div></div>The full source code for this demo <a href="http://source.tutsplus.com/gamedev/authors/VijayPemmaraju/flocking/Flocking.zip">can be downloaded here</a>, so this article will only highlight the most important aspects of the implementation. Feel free to <a href="http://source.tutsplus.com/gamedev/authors/VijayPemmaraju/flocking/Flocking.zip">download the source</a> if you wish to learn more. <br />
<hr /><h2>Alignment</h2><div><img alt="" height="145" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/vijay-pemmaraju/alignment600.png" title="alignment" width="600" /> Image adapted from <a href="http://www.red3d.com/cwr/boids/">Craig Reynolds’ article</a></div>Alignment is a behavior that causes a particular agent to line up with agents close by. First, we’ll make a function that takes an agent and returns a velocity vector. <br />
<pre>public function computeAlignment(myAgent:Agent):Point
{
}
</pre>We’ll need two variables: one for storing the vector we’ll compute, and another for keeping track of the number of neighbors of the agent. <br />
<pre>var v:Point = new Point();
var neighborCount = 0;
</pre>[...]<br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/the-three-simple-rules-of-flocking-behaviors-alignment-cohesion-and-separation/" target="_blank">Read more: The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and Separation</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-3444997754693509382013-01-15T08:55:00.001-08:002013-01-15T08:55:51.110-08:00Going Old School: Making Games With a Retro AestheticEverything old is new again, and retro games are more popular than ever. Bolstered by nostalgia and the abundance of casual and arcade-style games on iOS and Android devices, old school games are making a comeback. In this tutorial I’ll give you some tips on creating a successful retro-themed game.<br />
<hr /><h2>Choosing a Retro Style</h2>What do we mean when we talk about ‘retro’ games? There’s no concrete definition, but I typically think of games made before 1990. This includes games from consoles like the GameBoy, NES, Atari 2600, and Commodore 64, as well as classic arcade games like <i>Pac Man</i>, <i>Centipede</i>, and <i>Space Invaders</i>.<br />
All of those examples use blocky, pixelated, bitmap (or ‘raster’) graphics. These are the type of games that probably come to mind for most people when they think of retro games.<br />
<div><img alt="Retro Games with Raster Graphics" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/retroGames_Raster.jpg" /><br />
Raster Graphics: Pac Man (Arcade), Frogger (Atari 2600), Super Mario Bros. (GameBoy)</div>But the earliest video games actually used vector graphics. Games like <i>Battlezone</i>, <i>Asteroids</i> and <i>Tempest</i> were rendered with brightly glowing lines instead of blocky pixels.<br />
<div><img alt="Retro Games with Vector Graphics" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/retroGames_Vector.jpg" /><br />
Vector Graphics: Battlezone (Arcade), Tempest (Arcade), MineStorm (Vectrex)</div>Another type of game us old folks used to play were simple handheld games that used a monochrome LCD display and extremely simple game mechanics.<br />
<div><img alt="Retro Games with LCD Graphics" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/retroGames_LCD.jpg" /><br />
LCD Graphics: Donkey Kong Jr. (Game & Watch), Mario’s Cement Factory (Game & Watch)</div>In this tutorial, we’re going to talk about the more popular raster graphics games, but I mention these other types of games because they are not often emulated, and I think there is a lot of opportunity for game designers to do something really cool with those styles.<br />
<hr /><h2>Creating a Color Palette</h2>To create a convincing retro look, you’ll want to work with a limited set of colors.<br />
Old-school game consoles were only able to display a limited number of colors. Depending on the system, graphics would be shown in black and white, grayscale, or 8- or 16-bit color. You can see examples of the exact color palettes from specific systems on <a href="http://en.wikipedia.org/wiki/List_of_videogame_consoles_palettes">Wikipedia</a>, but it’s not important to choose historically accurate colors as long as you <a href="http://gamedev.tutsplus.com/tutorials/game-art/picking-a-color-palette-for-your-games-artwork/">maintain a consistent style</a> within your game.<br />
We don’t face the same hardware limitations we did in the past, but keeping your palette limited to a few carefully chosen colors will not only emphasize the retro aesthetic, it will also help to define the identity of your game. Look at these two examples of color palettes from <i>Super Mario Bros.</i>:<br />
<div><img alt="Color Palettes from Super Mario Bros." src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/retroGames_colorPalettes.jpg" /></div>The colors are so distinct, you can almost recognize the game just from the color swatches.<br />
David Sommers has a nice collection of classic game palettes at <a href="http://www.colourlovers.com/blog/2008/06/18/classic-color-palettes-video-games">ColourLovers.com</a>.<br />
The exact colors you choose will depend on the theme and mood of your game, but if you take the time to choose a good set of colors your game will feel as iconic as the classics. Take a look at these modern examples:<br />
<div><img alt="Modern Games with Retro Palettes" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/modernGamesWithLimitedPalettes.jpg" /><br />
<a href="http://www.adamatomic.com/canabalt/">Canabalt</a> by Adam Atomic, <a href="http://shauninman.com/lastrocket/">The Last Rocket</a> by Shaun Inman, <a href="http://polytroncorporation.com/what-is-fez">Fez</a> by Polytron</div>If you’re having trouble choosing colors that work well together, check out this great tutorial by Tyler Seitz, <a href="http://gamedev.tutsplus.com/tutorials/game-art/picking-a-color-palette-for-your-games-artwork/">Picking a Color Palette for Your Game’s Artwork</a>.<br />
<hr /><h2>Choosing a Pixel Size</h2>Retro raster games are most easily recognized by their big chunky pixels, from a time when screen resolutions were much lower. In today’s world of HD screens and Retina displays, the physical pixels on our devices are barely visible – not nearly prominent enough to get the retro blocky look.<br />
<div><img alt="Scaling Up a Game Sprite" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/29/spriteScales.jpg" /><br />
In this example each pixel from our character graphic is being displayed on screen with four physical pixels.</div>To account for this, we need to use multiple physical pixels to display each visible pixel in our game graphics.<br />
<div><img alt="Different Scale Factors" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/30/retroGame_scaleFactors.jpg" /></div>You can decide what level of scaling is appropriate for your game depending on how blocky you want your game to look. Usually scaling up to two or three times normal size gives a good effect. Keep in mind that the bigger you go, the less you’ll be able to fit on the screen.<br />
I recommend that you always let your game engine do your pixel scaling for you. This means that all your assets and text are drawn at 100% (small) and the game simply scales up the entire game canvas to get to the final size. You could actually draw assets with larger pixels, but this will increase file sizes and load times, and can also have a negative impact on game performance.<br />
[...] <br />
<a href="http://gamedev.tutsplus.com/tutorials/aesthetics/going-old-school-making-games-with-a-retro-aesthetic/" target="_blank">Read more: Going Old School: Making Games With a Retro Aesthetic</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-55035653824306357992013-01-14T12:41:00.001-08:002013-01-14T12:42:07.514-08:00Parsing and Rendering Tiled TMX Format Maps in Your Own Game EngineIn <a href="http://gamedev.tutsplus.com/tutorials/level-design/introduction-to-tiled-map-editor/">my previous article</a>, we looked at <a href="http://www.mapeditor.org/">Tiled Map Editor</a> as a tool for making levels for your games. In this tutorial, I’ll take you through the next step: parsing and rendering those maps in your engine. <i><b>Note:</b> Although this tutorial is written using Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.</i> <br />
<hr /><h2>Requirements</h2><ul><li>Tiled version 0.8.1: <a href="http://www.mapeditor.org/">http://www.mapeditor.org/</a></li>
<li>TMX map and tileset from <a href="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Nick%20Bruner/2012/11/27/tileset.zip">here</a>. If you followed my <a href="http://gamedev.tutsplus.com/tutorials/level-design/introduction-to-tiled-map-editor/">Introduction to Tiled</a> tutorial you should already have these.</li>
</ul><hr /><h2>Saving in XML Format</h2>Using the TMX specification we can store the data in a variety of ways. For this tutorial we will be saving our map in the XML format. If you plan on using <a href="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Nick%20Bruner/2012/11/27/tileset.zip">the TMX file included in the requirements section</a> you can skip to the next section. If you made your own map you will need to tell Tiled to save it as XML. To do this, open your map with Tiled, and select Edit > Preferences… For the “Store tile layer data as:” dropdown box, select XML, as shown in the image below: <br />
<div><img alt="" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Nick%20Bruner/2012/12/12/saveasxml.png" /></div>Now when you save the map it will be stored in XML format. Feel free to open the TMX file with a text editor to take a peek inside. Here’s a snippet of what you can expect to find: <br />
<pre><map version="1.0" orientation="orthogonal" width="20" height="20" tilewidth="32" tileheight="32">
<tileset firstgid="1" name="grass-tiles-2-small" tilewidth="32" tileheight="32">
<image source="grass-tiles-2-small.png" width="384" height="192"/>
</tileset>
<tileset firstgid="73" name="tree2-final" tilewidth="32" tileheight="32">
<image source="tree2-final.png" width="256" height="256"/>
</tileset>
<layer name="Background" width="20" height="20">
<data>
<tile gid="13"/>
<tile gid="2"/>
<tile gid="1"/>
...
</data>
</layer>
<layer name="Top" width="20" height="20">
<data>
<tile gid="0"/>
...
</data>
</layer>
<objectgroup name="Collision" width="20" height="20">
<object x="287" y="354" width="127" height="60"/>
</objectgroup>
</map>
</pre>As you can see, it simply stores all the map information in this handy XML format. The properties should mostly be straightforward, with the exception of <code>gid</code> – I will go into a more in-depth explanation of this later on in the tutorial. Before we move on, I would like to direct your attention to the <code>objectgroup</code> “<code>Collision</code>” element. As you may recall from the <a href="http://gamedev.tutsplus.com/tutorials/level-design/introduction-to-tiled-map-editor/">map creation tutorial</a>, we specified the collision area around the tree; this is how it is stored. You can specify power-ups or player spawn point in the same manner, so you can imagine how many possibilities there are for Tiled as a map editor! <br />
<hr /><h2>Core Outline</h2>Now here’s a brief rundown on how we will be getting our map into the game: <br />
<ol><li>Read in the TMX file.</li>
<li>Parse the TMX file as an XML file.</li>
<li>Load all the tileset images.</li>
<li>Arrange the tileset images into our map layout, layer by layer.</li>
<li>Read map object.</li>
</ol><hr /><h2>Reading in the TMX File</h2>As far as your program is concerned, this is just an XML file, so the first thing we want to do is read it in. Most languages have an XML library for this; in the case of AS3 I will use the <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html">XML class</a> to store the XML information and a <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6">URLLoader</a> to read in the TMX file. <br />
<pre>xmlLoader=new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlLoadComplete);
xmlLoader.load(new URLRequest("../assets/example.tmx"));
</pre>This is a simple file reader for <code>"../assets/example.tmx"</code>. It assumes that the TMX file is located in your project directory under the “assets” folder. We just need a function to handle when the file read is complete: <br />
<pre>private function xmlLoadComplete(e:Event):void {
xml = new XML(e.target.data);
mapWidth = xml.attribute("width");
mapHeight = xml.attribute("height");
tileWidth = xml.attribute("tilewidth");
tileHeight = xml.attribute("tileheight");
var xmlCounter:uint = 0;
for each (var tileset:XML in xml.tileset) {
var imageWidth:uint = xml.tileset.image.attribute("width")[xmlCounter];
var imageHeight:uint = xml.tileset.image.attribute("height")[xmlCounter];
var firstGid:uint = xml.tileset.attribute("firstgid")[xmlCounter];
var tilesetName:String = xml.tileset.attribute("name")[xmlCounter];
var tilesetTileWidth:uint = xml.tileset.attribute("tilewidth")[xmlCounter];
var tilesetTileHeight:uint = xml.tileset.attribute("tileheight")[xmlCounter];
var tilesetImagePath:String = xml.tileset.image.attribute("source")[xmlCounter];
tileSets.push(new TileSet(firstGid, tilesetName, tilesetTileWidth, tilesetTileHeight, tilesetImagePath, imageWidth, imageHeight));
xmlCounter++;
}
totalTileSets = xmlCounter;
}
</pre>This is where the initial parsing is taking place. (There are a few variables we will keep track of outside this function since we will use them later.) Once we have the map data stored, we move onto parsing each tileset. I’ve created a class to store each tileset’s information. We’ll push each of those class instances in an array since we will be using them later: <br />
<pre>public class TileSet
{
public var firstgid:uint;
public var lastgid:uint;
public var name:String;
public var tileWidth:uint;
public var source:String;
public var tileHeight:uint;
public var imageWidth:uint;
public var imageHeight:uint;
public var bitmapData:BitmapData;
public var tileAmountWidth:uint;
public function TileSet(firstgid, name, tileWidth, tileHeight, source, imageWidth, imageHeight)
{
this.firstgid = firstgid;
this.name = name;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.source = source;
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
tileAmountWidth = Math.floor(imageWidth / tileWidth);
lastgid = tileAmountWidth * Math.floor(imageHeight / tileHeight) + firstgid - 1;
}
}
</pre>Again, you can see that <code>gid</code> appears again, in the <code>firstgid</code> and <code>lastgid</code> variables. Let’s now look at what this is for. <br />
<hr /><h2>Understanding “<code>gid</code>“</h2>For each tile, we need to somehow associate it with a tileset and a particular location on that tileset. This is the purpose of the <code>gid</code>. Look at the <code>grass-tiles-2-small.png</code> tileset. It contains 72 distinct tiles: <br />
<div><img alt="" src="http://cdn.tutsplus.com/gamedev.tutsplus.com/authors/michael-james-williams/grass-tiles-2-small.png" /></div>We give each of these tiles a unique <code>gid</code> from 1-72, so that we can refer to any one with a single number. However, the TMX format only specifies the first <code>gid</code> of the tileset, since all of the other <code>gid</code>s can be derived from knowing the size of the tileset and the size of each individual tile. Here’s a handy image to help visualize and explain the process. <br />
<div><img alt="" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Nick%20Bruner/2012/12/12/gidexplained.png" /></div>So if we placed the bottom right tile of this tileset on a map somewhere, we would store the <code>gid</code> 72 at that location on the map. Now, in the example TMX file above, you will notice that <code>tree2-final.png</code> has a <code>firstgid</code> of 73. That’s because we continue counting up on the <code>gid</code>s, and we don’t reset it to 1 for each tileset. In summary, a <code>gid</code> is a unique ID given to each tile of each tileset within a TMX file, based on the position of the tile within the tileset, and the number of tilesets referred to in the TMX file. <br />
<hr /><h2>Loading the Tilesets</h2>Now we want to load all the tileset source images into memory so we can put our map together with them. If you aren’t writing this in AS3, the only thing you need to know is that we’re loading the images for each tileset here: <br />
<pre>// load images for tileset
for (var i = 0; i < totalTileSets; i++) {
var loader = new TileCodeEventLoader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, tilesLoadComplete);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.tileSet = tileSets[i];
loader.load(new URLRequest("../assets/" + tileSets[i].source));
eventLoaders.push(loader);
}
</pre><br />
[...] <br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/parsing-tiled-tmx-format-maps-in-your-own-game-engine/" target="_blank">Read more: Parsing and Rendering Tiled TMX Format Maps in Your Own Game Engine</a> Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-33881052939461740132012-12-17T13:50:00.001-08:002012-12-17T13:50:45.982-08:00Using Torque and Thrusters to Move and Rotate a Player-Designed SpaceshipWhile working on a game in which the spaceships are designed by players and can be partially destroyed, I encountered an interesting problem: moving a ship around using thrusters is not an easy task. You could simply move and rotate the ship around like a car, but if you want ship design and structural damage to affect ships’ movement in a believable way, actually simulating thrusters could be a better approach. In this tutorial, I’ll show you how to do this.<br />
Assuming a ship can have multiple thrusters in various configurations, and that the ship’s shape and physical properties can change (for example, parts of the ship could be destroyed), it is necessary to determine <i>which</i> thrusters to fire in order to move and rotate the ship. That’s the main challenge we need to tackle here.<br />
The demo is written in <a href="http://haxe.org/">Haxe</a>, but the solution can easily be implemented in any language. A physics engine similar to <a href="http://box2d.org/">Box2D</a> or <a href="http://code.google.com/p/nape/">Nape</a> is assumed, but any engine that provides the means to apply forces and impulses and query the physical properties of bodies will do.<br />
<hr /><h2>Try the Demo</h2><div></div>Click the SWF to give it focus, then use the arrow keys and the Q and W keys to activate different thrusters. You can switch to different spaceship designs using the 1-4 number keys, and you can click any block or thruster to remove it from the ship.<br />
<hr /><h2>Representing the Ship</h2>This diagram shows the classes that represent the ship, and how they relate to each other:<br />
<div><img alt="Gamedev Maths and Physics: Using Torque and Thrusters to Correctly Maneuver a Player-Designed Spaceship" src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Nemanja%20Stojanovic/2012/11/30/ship_class_dia1.1.png" /></div><code>BodySprite</code> is a class that represents a physical body with a graphical representation. It allows display objects to be attached to shapes, and makes sure that they move and rotate correctly with the body.<br />
The <code>Ship</code> class is a container of modules. It manages the structure of the ship and deals with attaching and detaching modules. It contains a single <code>ModuleManager</code> instance.<br />
Attaching a module attaches its shape and display object to the underlying <code>BodySprite</code>, but removing a module requires a bit more work. First the module’s shape and display object are removed from the <code>BodySprite</code>, and then the structure of the ship is checked so that any modules not connected to the core (the module with the red circle) are detached. This is done using an algorithm similar to <a href="http://en.wikipedia.org/wiki/Flood_fill">flood fill</a> that takes into account the way each module can connect to other modules (for example, thrusters can only connect from one side, depending on their orientation).<br />
Detaching modules is somewhat different: their shape and display object are still removed from the <code>BodySprite</code>, but are then attached to an instance of <code>ShipDebris</code>.<br />
This way of representing the ship is not the simplest, but I found it to work very well. The alternative would be to represent each module as a separate body and “glue” them together with a weld joint. While this would make breaking the ship apart much easier, it would also cause the ship to feel rubbery and elastic if it had a large number of modules.<br />
The <code>ModuleManager</code> is a container that keeps the modules of a ship in both a list (allowing easy iteration) and a hash map (allowing easy access via local coordinates).<br />
The <code>ShipModule</code> class obviously represents a ship module. It’s an abstract class that defines some convenience methods and attributes that each module has. Each module subclass is responsible for constructing its own display object and shape, and for updating itself if needed. Modules are also updated when they’re attached to <code>ShipDebris</code>, but in that case the <code>attachedToShip</code> flag is set to <code>false</code>.<br />
So a ship is really just a collection of functional modules: building blocks whose placement and type defines the behavior of the ship. Of course, having a pretty ship just floating around like a pile of bricks would make for a boring game, so we need to figure out how to make it move around in a way that is fun to play and yet convincingly realistic.<br />
<hr /><h2>Simplifying the Problem</h2>Rotating and moving a ship by selectively firing thrusters, varying their thrust either by adjusting throttle or by turning them on and off in quick succession, is a difficult problem. Fortunately, it is also an unnecessary one.<br />
If you wanted to rotate a ship precisely around a point, for example, you could do that simply by telling your physics engine to rotate the whole body. In this case, however, I was looking for a simple solution that isn’t perfect, but is fun to play. To make the problem simpler, I’ll introduce a constraint:<br />
<blockquote>Thrusters can only be on or off and they can’t vary their thrust.</blockquote>Now that we’ve abandoned perfection and complexity, the problem is a lot simpler. We need to determine, for each thruster, whether it should be on or off, depending on its position on the ship and the player’s input. We could assign a different key for each thruster, but we’d end up with an interstellar QWOP, so we’ll use the arrow keys for turning and moving, and Q and W for strafing.<br />
<hr /><h2>The Simple Case: Moving the Ship Forwards and Backwards</h2>The first order of business is to move the ship forwards and backwards, as this is the simplest possible case. To move the ship, we’ll simply fire the thrusters facing in the direction opposite to the one we want to go. For example, if we wanted to go forward, we’d fire all the thrusters that face backwards.<br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/using-torque-and-thrusters-to-move-and-rotate-a-player-designed-spaceship/" target="_blank">Read more: Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-6432122263176055702012-12-17T13:46:00.001-08:002012-12-17T13:47:33.638-08:00Flash Haxe Gaming SDK, their tools, our toolsSo Adobe released a few weeks ago its <a href="http://gaming.adobe.com/technologies/gamingsdk/" title="null">Gaming SDK for flash</a>. The package includes Starling, Away3D and Feathers, three well know quality open source ActionScript3 libraries. You can easily find some externs for most of them on <a href="http://lib.haxe.org/" title="null">http://lib.haxe.org</a>, which is great! However, during the development of my last game (which used Starling and Haxe) I found out that using haxelibs wasn't enough. A lot of good stuff is happening in the AS3 side, Starling is improving day after day on Github, users create really useful extensions for it. Time is precious and we don't want to write externs for everything or rewrite everything in haxe do we? Thanks to the great haxe/flash support, we can easily use all the good stuff in a matter of seconds, we can hack AS3 code and use the result from Haxe too. In this post I will try to teach beginners how to fish AS3 :) <br />
<ul><li>how to compile a bunch of .as files into a .swf using the Flex SDK.</li>
<li>how to use those .swf files in haxe (with no extra work)</li>
<li>how to patch things when haxe is not happy with the .swf</li>
</ul>We'll end up with the entire <b>Adobe Gaming SDK, and more, for Haxe</b>. But the journey is more important than the destination. NOTE: If you are not interested in the process and just want the SDK, I created a bunch of github repositories to host the results. See the test repository to learn how to play with it <a href="https://github.com/labe-me/haxe-gaming-sdk-test" title="null">https://github.com/labe-me/haxe-gaming-sdk-test</a> NOTE: I do not intend to write any extern for these libraries (I am too lazy for that), hence I won't submit them to haxelib. Feel free to use my work in any way you want to create nice haxelib packages. As far as I am concerned I really enjoy the haxelib git support :) Start. We are going to compile <code>.as</code> files, you'll need to install the <a href="http://www.adobe.com/devnet/flex/flex-sdk-download.html" title="null">Flex SDK</a>. Let's learn how it works with Starling. (1) get the library sources: <br />
[...] <a href="http://labe.me/en/blog/posts/2012-12-17-flash-haxe-gaming-sdk.html" target="_blank">read more: Flash Haxe Gaming SDK, their tools, our tools</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-61742846452206532452012-12-13T16:36:00.001-08:002012-12-13T16:37:06.969-08:00Creating a Custom Virtual KeyboardAlthough AIR for iOS offers access to the iOS virtual keyboard, you have limited control over the type of keyboard that appears. If you want additional keyboard configurations within your Flash project then you’ll need to build your own custom keyboard component. Although this will require some development effort it will allow you to tailor the user experience. For certain apps such as games, you may actually find a custom keyboard is the preferred option, as it will better fit your visual design.<br />
Let’s see how to create one using Flash.<br />
<div style="border-bottom: 1px dotted #555555; border-top: 1px dotted #555555; height: 140px; padding-bottom: 5px; padding-top: 5px;"><img alt="Flash iOS Apps Cookbook" height="130" src="http://www.yeahbutisitflash.com/wp-content/uploads/2012/04/cookbook-cover.png" title="Flash iOS Apps Cookbook" width="105" /><b>This tutorial is a previously unreleased recipe from <a href="http://www.amazon.com/gp/product/184969138X/ref=s9_simh_gw_p14_d0_g14_i1?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=18SPM3FGKR4M407BHZ2M&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846">Flash iOS Apps Cookbook</a> and supplements the content found in Chapter 7, Working with Text and the Virtual Keyboard.</b><br />
Flash iOS Apps Cookbook provides the recipes required to build native iOS apps using your existing knowledge of the Flash platform. Whether you want to create something new or simply convert an existing Flash project, the relevant steps and techniques are covered, helping you achieve your goal. </div><h2>Getting Ready</h2>An FLA has been provided as a starting point.<br />
Download this recipe’s <a href="http://www.yeahbutisitflash.com/downloads/flash-ios-apps-cookbook/chapter7.zip">accompanying source bundle</a> and open <code>chapter7/recipe8/recipe.fla</code> into Flash Professional.<br />
The visuals for this application have already been created. Sitting on the stage is a virtual keyboard and a dynamic text field. The text field will be used to output what the user types.<br />
The dynamic text field has been named <code>field</code> while the movie clip instance that represents the virtual keyboard has been named <code>keyboard</code>.<br />
<div style="width: 580px;"><a href="http://www.yeahbutisitflash.com/wp-content/uploads/2012/12/screenshot1.png"><img alt="" height="287" src="http://www.yeahbutisitflash.com/wp-content/uploads/2012/12/screenshot1.png" title="screenshot1" width="570" /></a><br />
Entering a player's name with a custom virtual keyboard.</div>With the Selection tool (V) selected, double-click on the <code>keyboard</code> instance to examine its timeline. The keyboard contains 28 keys – 26 for the letters of the alphabet, an <i>ok</i> key for when the user is finished typing, and a <i>del</i> key to delete a character. You’ll find that each alphabetic key is represented by its own movie clip and that the instances are named <code>a_key</code> to <code>z_key</code>. This naming convention makes it easy to determine the letter that a key represents by simply examining the first character of its instance name. The remaining two keys have instance names of <code>ok_key</code> and <code>del_key</code>. Additionally there’s a movie clip named <code>surface</code> that sits beneath the keys and represents the keyboard’s body.<br />
Double-click on any one of the keys to examine its timeline. Each is represented by two frames, where the second frame will be shown when the key is being pressed. The movie clip symbol for each key is linked to a class named <code>Button</code>, which was introduced in the <i>Handling user interaction</i> recipe from Chapter 4. Open <code>Button.as</code> and familiarize yourself with the code.<br />
<h2>How to do it…</h2>Perform the following steps.<br />
From Flash, select <b>File | New</b> and create a new ActionScript 3.0 class. Name it <code>VirtualKeyboard</code>.<br />
<li>Add the following ActionScript to the class:<br />
[...]<br />
<a href="http://www.yeahbutisitflash.com/?p=4602" target="_blank">Read more: Creating a Custom Virtual Keyboard</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-61352564267506392152012-12-12T11:34:00.001-08:002012-12-12T11:35:15.538-08:00Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler<a href="http://gaming.adobe.com/technologies/scout/">Adobe Scout</a> allows developers to profile SWFs like never before. The telemetry data sent by the release Flash Player to Adobe Scout is by default only set to send basic telemetry data. To be able to see data for the AS3 sampler, Stage3D rendering, and DisplayList rendering you have to enable the SWF (password is optional).<br />
This is done by using the newer asc2 compiler that comes in Flash Builder 4.7 or in the AIR sdk found in the <a href="http://gaming.adobe.com/technologies/gamingsdk/">Gaming SDK</a> from <a href="http://www.adobe.com/products/creativecloud.html">Creative Cloud</a>. Currently asc2 only works with ActionScript projects and implements a new flag called -advanced-telemetry or a check box in Flash Builder 4.7 ActionScript project properties.<br />
To enable SWFs that don’t use asc2, mainly Flex apps or legacy SWFs, you need to use a script to write a specific SWF tag into the SWF file. This doesn’t change the SWF abc code but just adds a SWF tag that Flash Player will use to start sending telemetry data. There is a python script written to help with writing this tag. But the python script requires python and I wanted something a bit easier to use so I created <a href="https://github.com/downloads/renaun/ActionScriptExamples/SWFScoutEnabler.air">SWF Scout Enabler</a>.<br />
<a href="http://renaun.com/blog/wp-content/uploads/2012/12/swfscoutenabler.png"><img alt="" src="http://renaun.com/blog/wp-content/uploads/2012/12/swfscoutenabler.png" title="SWF Scout Enabler" width="540" /></a><br />
To use the application all you need to do is drag your SWF into the application and it will create a new SWF (or override if you give it a “” suffix) that is enabled for advanced telemetry.<br />
The application will also save the last suffix and password used. It also has the ability to re-process the last processed file by clicking on the top right box image.<br />
Last but not least, the full source of the application can be found on <a href="https://github.com/renaun/ActionScriptExamples/tree/master/SWFScoutEnabler">github</a>.<br />
Download the <a href="https://github.com/downloads/renaun/ActionScriptExamples/SWFScoutEnabler.air">SWF Scout Enabler AIR application</a>.<br />
I need to thank <a href="http://josephlabrecque.com/">Joseph Labrecque</a> for testing out the app.<br />
Note: This app has been tested on a bunch of SWFs but if it is not working let me know. There seems to be a bug with Adobe Scout on AS2 SWFs older than version 8. Adobe Scout will never do ActionScript sampling on AS2 SWFs but it will do basic telemetry.<br />
<br />
<a href="http://renaun.com/blog/2012/12/enable-advanced-telemetry-on-flex-or-old-swfs-with-swf-scount-enabler/" target="_blank">Read more: Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-72056992691007162572012-12-11T13:03:00.001-08:002012-12-11T13:04:08.764-08:00Animating With Asset Sheets: An Alternative to BlittingSo you’ve got your awesome game in the works, it’s got all sorts of complex physics, epic enemy AI or what-have-you. But it feels lifeless. You want some OOMPH, you want some animation!<br />
So if you go and look up how to animate, the first answer you come across will most likely be a method using spritesheets and blitting. In fact, almost all tutorials on the web talk about nothing <i>but</i> blitting, as if there’s no other way to animate. But in my experience, there’s a better way to animate your orcs and goblins!<br />
This method could be called <i>animating with asset-sheets</i> – or more technically, <i>tweening</i> with asset-sheets – as opposed to using <i>sprite</i>-sheets. Before we get into exactly what this means, let’s consider an important question:<br />
<hr /><h2>What’s Wrong With Blitting?</h2>Below are some reasons as to <i>why</i> you would not want to use blitting in certain cases.<br />
<h3>1. It Takes a Lot of Space</h3>Whether we’re talking about RAM or disk space, sprite sheets can easily clog things up. Especially if you’re trying to make HD graphics. Huge sprite sheets may have to be split into multiple PNGs, taking up precious RAM and skyrocketing your game’s size if you’re not careful.<br />
<h3>2. It’s Not Dynamic</h3>What happens when you want to speed up an animation? You could skip some frames, but what about slowing down? The animation would look choppy and ugly. Even if you want to only support 60 fps, what if a computer can run the game faster? You could have jaw-droppingly smooth animations at higher frame rates with no extra work, and it would also look good if you chose to change the game’s frame rate at any time.<br />
And what if you wanted something to happen when the player’s arms reached some place? Or to have him pick up something? You’d need to manually mark his arm throughout the animation, which may be time-consuming as you can’t get any data about where any of his limbs are from a sprite sheet.<br />
<h3>3. It Doesn’t Allow You to Make Transitions</h3>What happens when the player is running and suddenly jumps? It cuts to the jump animation right away. This looks choppy, and this would happen every time the animation transitions to a new state. You’d have to make a transition for every pair of animations you have, which is not only insanely time consuming, but also has the adverse effect of increasing your RAM usage as discussed earlier.<br />
<hr /><h2>The Alternative</h2>Using asset-sheets not only allows the animations to be dynamic and scale up with any FPS, as well as transitioning smoothly between any two states, but <i>also</i> takes a tiny tiny amount of disk space and RAM compared to blitting!<br />
This isn’t even very new. Some popular games use it, like the recently popular <a href="http://closuregame.com/">Closure</a>. Its only limitation is that it can’t do frame-by-frame (FBF) animation, since it relies on tweening – so if you have complex explosions, you’ll have to use sprite sheets.<br />
But for a lot of cases, you’ll find you won’t need to, and it’s more than worth the effort to have a system like this for your game, as some games could rely completely on this, shaving off a ton of overhead. It’s also really cool because it’s similar to how you might animate a 3D game!<br />
So to summarize:<br />
<div><img alt="Gamedev Animation With Asset-Sheets: An Alternative to Blitting" src="http://gamedevtuts.s3.amazonaws.com/050_assetSheets/Asset_Sheets_vs_Sprite_Sheets.png" /></div><hr /><h2>Let’s Dive Right In</h2>This is a character and his asset sheet.<br />
<div><img alt="Gamedev Animation With Asset-Sheets: An Alternative to Blitting" src="http://gamedevtuts.s3.amazonaws.com/050_assetSheets/Asset_Sheet.png" /></div>As the name implies, an asset sheet is a PNG with all the limbs/assets of the character or object separated.<br />
And here is the animation data in JSON (of course, you can use whichever format you prefer to work with):<br />
<pre>//this snippet shows the first three frames of the "Body" animation
"-name":"Body",
"Frame": [
{
"-x":"0.65",
"-y":"-64.45",
"-rotation":"0.000"
},
{
"-x":"2.45",
"-y":"-64.45",
"-rotation":"0.279"
},
"-x":"3.30",
"-y":"-64.05",
"-rotation":"0.707"
}
</pre>Now combining these two together in an awesome engine, you get:<br />
<div><img alt="Gamedev Animation With Asset-Sheets: An Alternative to Blitting" src="http://gamedevtuts.s3.amazonaws.com/050_assetSheets/Animating-With-Asset-Sheets.gif" /></div>And unlike a blitted animation, this could speed down or up, or transition very smoothly. So this is what we'll be doing.<br />
<hr /><h2>Step 1: Exporting Your Asset Sheet</h2>The first step is to get your asset-sheet ready. You can do this in any number of ways. The point is to end up with a sheet containing the assets and a data file containing the positions of the assets in the sheet. This is the exact same method as for making a spritesheet, except in lieu of sprites you add separate assets.<br />
Export your player's limbs and pieces as individual PNGs, then use a program like <a href="http://www.codeandweb.com/texturepacker">Texture Packer</a> to group them into a sheet. There are other programs, but I personally prefer Texture Packer because of how versatile and feature-rich it is.<br />
<b>Tip:</b> Whatever software you use to make your sheets , make sure there is at least 2px of padding between each asset and 1px extrusion. This will prevent some nasty problems in the future.<br />
<hr /><h2>Step 2: Exporting Your Animation Data</h2>[...]<br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/animating-with-asset-sheets-an-alternative-to-blitting/" target="_blank">Read more: Animating With Asset Sheets: An Alternative to Blitting</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-9034604597669501152012-12-04T13:22:00.001-08:002012-12-04T13:24:12.560-08:00Introducing Game Developer ToolsI am really excited about what happened tonight. We just announced the introduction of the Adobe Game Developer Tools on Creative Cloud. You can read the official announcement <a href="http://blogs.adobe.com/digitalmedia/2012/12/adobe-delivers-new-game-developer-tools-in-creative-cloud/" title="Adobe delivers new game developer tools in Creative Cloud">here</a>. As part of this, we are introducing three new products: Adobe <a href="http://gaming.adobe.com/technologies/gamingsdk" title="Gaming SDK">Gaming SDK</a>, <a href="http://gaming.adobe.com/technologies/flascc" title="FlasCC">FlasCC</a> and <a href="http://gaming.adobe.com/technologies/scout" title="Adobe Scout">Adobe Scout</a>, which I have been working on for a year now. Here is a video about Adobe Scout and why it is going to change everything for your as a developer: <iframe frameborder="0" height="410" src="http://www.youtube.com/embed/NybbHVxfLLI?hd=1" width="728"></iframe> I wrote a <a href="http://www.adobe.com/devnet/flashruntimes/articles/adobe-scout-getting-started.html" title="Getting Started with Adobe Scout">full article on how to get started with Scout</a>. Make sure you check it out! If you have any questions, check the <a href="http://forums.adobe.com/community/game_developers/adobe_scout" title="Adobe Scout Forums">Scout forums</a>! If you want to take a deep dive in Scout you can also check the video tutorials <a href="https://vimeo.com/channels/431654" title="Adobe Scout Vimeo Channel">here</a>. We also wanted to provide a great out of the box experience for developers to get started with the stack. Provide a nice package that allowa developers to get up and running quickly without having to hunt for the frameworks needed, the compilers and right documentation. That's why we are also introducing the <a href="http://gaming.adobe.com/technologies/gamingsdk" title="Gaming SDK">Gaming SDK</a>: <iframe frameborder="0" height="410" src="http://www.youtube.com/embed/hJdrZeqqGZU" width="728"></iframe> The Gaming SDK contains the key frameworks you guys need to use to create fast performing 2D and 3D GPU games, but also much more, from the ATF tools to iOS ANEs. <a href="http://www.bytearray.org/starling-framework.org" title="Starling Framework">Starling</a>, <a href="http://www.feathersui.com/" title="Feathers">Feathers</a> and <a href="http://www.away3d.com/" title="Away3D">Away3D</a> are officially supported by Adobe and part of the Gaming SDK. It provides to you a one stop shop package to get started with the technology, we hope you guys will enjoy it! For those of you guys doing native development and interested in porting native games to the desktop, you can now use <a href="http://gaming.adobe.com/technologies/flascc" title="FlasCC">FlasCC</a> (formerly named Alchemy), which is now release quality and supported. <br />
<br />
<a href="http://www.bytearray.org/?p=4969" target="_blank">Read more: Introducing Game Developer Tools</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-69563528584126846022012-11-30T12:52:00.001-08:002012-11-30T12:52:53.428-08:00How to make a Facebook social gameHi and welcome back to my blog!<br />
This time I’m going to talk about the process of making a very basic social game as a Facebook app. <br />
It’s my hope that if you know how to make a Flash game and have a little bit of PHP/database experience by the end of the article you will be set to make your first Facebook app.<br />
This is a technical article covering the implementation of some of the core social game subsystems and not intended to be a discussion about moral justification of social game mechanics or even about how to design a social game – I’ll leave those aspects to game-designers and the media <img alt=":)" src="http://www.wildbunny.co.uk/blog/wp-includes/images/smilies/icon_smile.gif" /> <br />
The game I’m going to be making is called ‘Pet My Kitty’.<br />
<div style="width: 310px;"><a href="http://apps.facebook.com/pet_my_kitty/"><img alt="" height="270" src="http://www.wildbunny.co.uk/blog/wp-content/uploads/2012/11/screenShot-300x270.png" title="screenShot" width="300" /></a><br />
Click to play the live version of the game on Facebook</div><h2>Pet My Kitty</h2>In a nod to the now defunct mock-social game, <a href="http://en.wikipedia.org/wiki/Cow_Clicker">Cow Clicker</a> Pet My Kitty will have an absolute minimal set of functionality necessary to operate as a social game:<br />
<ul><li>Interactive mechanic</li>
<li>Database persistence</li>
<li>Ability to purchase an in-game item</li>
<li>Invite friends</li>
<li>Social marketing incentive</li>
</ul>Let’s quickly review each one of these points to elaborate on why they are key to a social game.<br />
<b>Interactive mechanic</b><br />
There has to be something interactive about a Facebook game, no matter how simple otherwise it wouldn’t classify as a game. Furthermore, there needs to be something visually rich and rewarding associated with each interaction, so the user understands they are doing things the right way. <br />
<a href="http://www.wildbunny.co.uk/blog/2012/11/30/how-to-make-a-facebook-social-game/" target="_blank">Read more: How to make a Facebook social game</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-7635568176025013872012-11-27T13:40:00.001-08:002012-11-27T13:41:22.581-08:00Using GDB script files with the FlasCC GDBThe <a href="http://gaming.adobe.com/technologies/flascc/">Flash C++ Compiler (FlasCC)</a> provides a complete BSD-like C/C++ development environment based on GCC that lets you compile your C/C++ code to target the Adobe® Flash® Runtime (Flash Player and AIR®). With FlasCC you can port almost any existing C/C++ code to the web, across browsers. FlasCC includes tools for building, testing, and debugging C/C++ projects, example projects with source code, and documentation. You can get FlasCC today on the <a href="http://gaming.adobe.com/technologies/flascc/">http://gaming.adobe.com/technologies/flascc/</a> page.<br />
Today I want to share a quick FlasCC debugging tip. The FlasCC based <code>gdb</code> tool is located in the FlasCC download under <code>sdk/usr/bin/gdb</code> (Mac) or <code>sdk/usr/bin/gdb.exe</code> (Win/Cygwin). <br />
Before trying this out we need a simple C app to debug. Go ahead and create a file called test.c and put the following code inside:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>C: <br />
<div><div><span style="color: #339933;">#include <stdio.h></span> <br />
<span style="color: #993333;">int</span> main<span style="color: #66cc66;">(</span><span style="color: #993333;">int</span> argc, <span style="color: #993333;">char</span> **argv<span style="color: #66cc66;">)</span><br />
<span style="color: #66cc66;">{</span><br />
<span style="color: #993333;">int</span> i = <span style="color: #cc66cc;">0</span>;<br />
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">(</span><span style="color: red;">"Hello World %d Time<span style="color: #000099; font-weight: bold;">\n</span>"</span>, i++<span style="color: #66cc66;">)</span>;<br />
<a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">(</span><span style="color: red;">"Hello World %d Time<span style="color: #000099; font-weight: bold;">\n</span>"</span>, i++<span style="color: #66cc66;">)</span>;<br />
<span style="color: #66cc66;">}</span></div></div></div>And the command to compile the debug SWF with FlasCC is:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div>sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf</div></div></div>The FlasCC <code>gdb</code> relies on an environmental variable called <code>FLASCC_GDB_RUNTIME</code>, if you do not set it before running <code>gdb</code> you'll see the following message inside of the <code>gdb</code> prompt:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div><span style="color: #006600; font-weight: bold;">(</span>gdb<span style="color: #006600; font-weight: bold;">)</span> run<br />
Starting program: hello.swf <br />
Please set the FLASCC_GDB_RUNTIME environment variable to the path to a debugger player or browser.</div></div></div>The <code>FLASCC_GDB_RUNTIME</code> needs to be set to the standalone debug Flash Player or to a browser that has a debug Flash Player. I recommend for the first time that you try using the FlasCC <code>gdb</code> to download a standalone debug Flash Player from <a href="http://www.adobe.com/support/flashplayer/downloads.html">here</a> and us it. I downloaded the Mac version and put in a folder called /Code, which means I would run this command in Ternimal before I call <code>gdb</code>:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div>export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app</div></div></div>Lets take a look at my command line to see how to put this all together:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div>renaun$ sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf<br />
renaun$ export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app<br />
renaun$ sdk/usr/bin/gdb test.swf<br />
GNU gdb <span style="color: #006600; font-weight: bold;">(</span>GDB<span style="color: #006600; font-weight: bold;">)</span> <span style="color: maroon;">7</span>.<span style="color: maroon;">3</span><br />
Copyright <span style="color: #006600; font-weight: bold;">(</span>C<span style="color: #006600; font-weight: bold;">)</span> <span style="color: maroon;">2011</span> Free Software Foundation, Inc.<br />
License GPLv3+: GNU GPL version <span style="color: maroon;">3</span> or later <http:<span style="color: #ff9933; font-style: italic;">//gnu.org/licenses/gpl.html></span><br />
This is free software: you are free to change and redistribute it.<br />
There is NO WARRANTY, to the extent permitted by law. Type <span style="color: #cc0000;">"show copying"</span><br />
and <span style="color: #cc0000;">"show warranty"</span> for details.<br />
This GDB was configured as <span style="color: #cc0000;">"--host=x86_64-apple-darwin10 --target=avm2-elf"</span>.<br />
For bug reporting instructions, please see:<br />
<http:<span style="color: #ff9933; font-style: italic;">//www.gnu.org/software/gdb/bugs/>...</span><br />
<span style="color: #006600; font-weight: bold;">(</span>gdb<span style="color: #006600; font-weight: bold;">)</span> b main<br />
No symbol table is loaded. Use the <span style="color: #cc0000;">"file"</span> command.<br />
Make breakpoint pending on future shared library load? <span style="color: #006600; font-weight: bold;">(</span>y or <span style="color: #006600; font-weight: bold;">[</span>n<span style="color: #006600; font-weight: bold;">]</span><span style="color: #006600; font-weight: bold;">)</span> y<br />
Breakpoint <span style="color: maroon;">1</span> <span style="color: #006600; font-weight: bold;">(</span>main<span style="color: #006600; font-weight: bold;">)</span> pending.<br />
<span style="color: #006600; font-weight: bold;">(</span>gdb<span style="color: #006600; font-weight: bold;">)</span> run<br />
Starting program: test.swf <br />
0xdddddddd in ?? <span style="color: #006600; font-weight: bold;">(</span><span style="color: #006600; font-weight: bold;">)</span> <br />
Breakpoint <span style="color: maroon;">1</span>, 0xf0000051 in main <span style="color: #006600; font-weight: bold;">(</span>argc=<span style="color: maroon;">0</span>, argv=0x200ff0<span style="color: #006600; font-weight: bold;">)</span> at test.c:<span style="color: maroon;">5</span><br />
<span style="color: maroon;">5</span> int i = <span style="color: maroon;">0</span>;<br />
<span style="color: #006600; font-weight: bold;">(</span>gdb<span style="color: #006600; font-weight: bold;">)</span></div></div></div>So I setup export to the debug Flash Player and then ran the gdb against the SWF. But once in side the <code>gdb</code> command prompt I still need to setup a break point. When trying to setup a break point before starting the SWF it will display another warning which needs a yes response. After responding with a yes I can then type run.<br />
Here is the trick, by using <code>gdb -x script.txt</code> we can run it all in one command. Instead of having to type in my break point each time or responding yes. This is how it works, create a script.txt file and put in the following <code>gdb</code> commands:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div>set breakpoint pending on<br />
b main<br />
r</div></div></div>The first line sets the default warning option to be yes so you dont have to worry about it not being set. The second command sets a break point at the main function. And the last command runs the <code>gdb</code>, telling it to start. The command to use the <code>gdb</code> script is below:<br />
<div><a href="http://renaun.com/blog#">PLAIN TEXT</a></div><div>CODE: <br />
<div><div>renaun$ sdk/usr/bin/gdb -x script.txt test.swf</div></div></div>Another handy command to put in script.txt is the <code>set as3namespace com.renaun.test</code> command. This is needed if you create a FlasCC SWC with a custom namespace.<br />
<br />
<center>© %FIRST Erickson - visit the <a href="http://www.renaun.com/"><renaun.com:flexblog text="{ ModelLocator.myThoughts }"/></a> </center><br />
<br />
<a href="http://renaun.com/blog/2012/11/using-gdb-script-files-with-the-flascc-gdb/" target="_blank">Read more: Using GDB script files with the FlasCC GDB</a> Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-90017027977195927012012-11-26T12:20:00.001-08:002012-11-26T12:21:26.183-08:00Quick Tip: The OOP Principle of Inheritance This entry is part 6 of 6 in the series <a href="http://gamedev.tutsplus.com/series/beginners-guide-to-oop/" title="Beginner's Guide to OOP">Beginner's Guide to OOP</a><br />
<br />
We’ve come a long way in <a href="http://gamedev.tutsplus.com/series/beginners-guide-to-oop/">this beginner’s guide to object-oriented programming</a>, discussing the principles of <i>cohesion</i>, <i>coupling</i>, <i>encapsulation</i>, and <i>abstraction</i>. In this final article, we’ll discuss the OOP principle of <i>inheritance</i> and its uses in game development. <i><b>Note:</b> Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.</i> <br />
<hr /><h2>What Is Inheritance?</h2><a href="http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">Inheritance</a> is the principle of class hierarchy. It is the ability for one object to take on the states, behaviors, and functionality of another object. A real-world example of inheritance is genetic inheritance. We all receive genes from both our parents that then define who we are. We share qualities of both our parents, and yet at the same time are different from them. Objects in OOP can do the same thing. <a href="http://en.wikipedia.org/wiki/Subclass_(computer_science)#Subclasses_and_superclasses">Parent classes</a> can have child classes (also known as superclasses and subclasses respectively) which can have the same properties of the parent class, and can define new states, behaviors, and functionality of their own. As an example, consider the following class that could be used as a parent class to different shapes: <br />
<pre>public class Shape {
protected int height;
protected int width;
public Shape(int h, int w) {
height = h;
width = w;
}
public int area() {
return height * width;
}
public int getHeight() { return height; }
public int getWidth() { return width; }
public void setHeight(int h) { return height; }
public void setWidth(int w) { return width; }
}
</pre>To extend this class to implement a triangle, it would look like this: <br />
<pre>public class Triangle extends Shape {
public Triangle(int h, int w) {
super(h, w);
}
public int area() {
return super.area() / 2;
}
}
</pre><code>Triangle</code> has all the same states and functions as <code>Shape</code>, but redefines the <code>area()</code> function to return the proper area of a <code>Triangle</code> (half base times height). The keyword <code>super</code> is used to reference the superclass and any of its states and functions. This is why we can use <code>super()</code> to call the constructor of the superclass and <code>super.area()</code> to call the <code>area()</code> function of the superclass. So, in this case, <code>super.area()</code> returns <code>height * width</code>. The <code>protected</code> keyword is the last <a href="http://www.tutorialspoint.com/java/java_access_modifiers.htm">access level modifier</a>. It acts like the private access level modifier but also allows any subclasses to have access to the variable or function. <br />
<hr /><h2>Why Is It Helpful?</h2>As you can see, inheritance can greatly help reduce code redundancy between similar objects by taking what those objects have in common and putting them in one place. This also creates more maintainable code because it helps to comply with the principle of <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> and to prevent the ripple effect in code changes. If all of this seems familiar, it’s probably because <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-abstraction/">abstraction</a> had very similar benefits (as well as most of the other principles of OOP). Abstraction is closely related to inheritance as an abstracted class can be used as a superclass to create subclasses. The only difference between an abstract class and a normal class is that an abstract class cannot be used to create an object. <br />
<hr /><h2>How to Apply It</h2>Lets go back to our three games one more time to describe how to apply inheritance. <br />
<h3>Asteroids</h3>Recall that we defined an abstract class for moving objects across a screen. Also <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-cohesion/">recall</a> that we defined a <code>Ship</code> class for the ship object. To apply inheritance to Asteroids, we can have the <code>Ship</code> class extend the <code>Movable</code> class as follows: <br />
<pre>/**
* The Ship Class
*/
public class Ship extends Movable {
/**
* Function to rotate the ship
*/
public void rotate() {
// Code that turns the ship
}
/**
* Function to fire
*/
public void fire() {
// Code to fire
}
}
</pre>The code needed to move the ship is taken care of in the <code>Movable</code> abstract class, so we can remove it from the <code>Ship</code> class. All the other objects for Asteroids could also inherit from the <code>Movable</code> class, making it extremely easy to change how to move an object. One thing to note about inheritance is the ability to have <a href="http://en.wikipedia.org/wiki/Multiple_inheritance">multiple inheritance</a>, or the ability of one class to inherit from multiple classes at the same time. Some languages allow it, others do not. Java is one of the languages that does not allow multiple inheritance. Therefore, you couldn’t have the Ship object inherit from both a <code>Moveable</code> class and a <code>Drawable</code> class. Make sure you are familiar with what your programming language allows before you try to design inheritance into your game. <br />
<h3>Tetris</h3>Inheritance can be applied to Tetris by having the Tetrimino and all of the game visuals inherit from the <code>Drawable</code> class, which we defined in the last article. <br />
<h3>Pac-Man</h3><a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-intro-to-object-oriented-programming-for-game-development/">Recall</a> that for Pac-Man we identified thee objects: Pac-Man, a Ghost, and a pac-dot. Throughout this series we’ve only discussed these three objects and have put off mentioning anything about the last critical piece of Pac-Man: the power pellet. With inheritance, we are now ready to talk about it. A power pellet is a special pac-dot that allows Pac-Man to eat ghosts. Its states and behaviors are exactly the same as a pac-dot, with really the only difference being its size and the ability to blink (remember that to keep the game <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-coupling/">loosely coupled</a>, we want another class to monitor when a power pellet is eaten and active the <code>changeState()</code> method of the ghosts). This is when inheritance comes in handy. Since a pac-dot and power pellet are practically the same object, we can create a <code>PowerPellet</code> class which extends the <code>PacDot</code> class. The <code>PowerPellet</code> class would just need to modify a few states to make it bigger and add the behavior of growing and shrinking to create a blinking effect. And that’s it – we now have a power pellet with little extra work. Not too shabby. The code for how this would look could be as follows: <br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-inheritance/" target="_blank">Read more: Quick Tip: The OOP Principle of Inheritance</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-18076286199794492352012-11-20T12:26:00.001-08:002012-11-20T12:26:30.778-08:00How to make a multi-player game – part 2Hello and welcome back to my blog! This is part 2 in the series where I talk about making a multi-player game.<br />
Last time we built a TCP socket server in node.js and we’re able to send and receive complex types. <a href="http://www.wildbunny.co.uk/blog/2012/10/09/how-to-make-a-multi-player-game-part-1/">Read the first article if you’ve not already done so here</a>.<br />
Here is a <b>live version</b> of the game I’m describing in this series:<br />
<h2>Clock synchronisation</h2>It’s important that both the client and server’s clocks are synchronised because if there is any time based interpolation, you want both server and client to agree on what time it is and therefore at what position your interpolated object is.<br />
<div style="width: 305px;"><a href="http://www.wildbunny.co.uk/blog/wp-content/uploads/2012/11/figure11.png"><img alt="" height="286" src="http://www.wildbunny.co.uk/blog/wp-content/uploads/2012/11/figure11.png" title="figure1" width="295" /></a><br />
Asteroids on an interpolation orbit</div>I use this technique in <a href="http://2dspacemmo.wildbunny.co.uk/">2D Space MMO</a> to ensure the orbiting asteroids are in the same position across all clients and on the server. The asteroids are actually interpolating on an orbit around a central location – there are no update messages getting sent to correct their positions, the only thing which keeps them synchronised is having the same time value across all clients and server.<br />
Before we can try to synchronise clocks, we need to be sure we’re using the same concept of time on both server and client. We want to calculate the number of seconds since 1970/01/01, which is the same in both javascript and actionscript:<br />
<a href="http://www.wildbunny.co.uk/blog/2012/11/20/how-to-make-a-multi-player-game-part-2/" target="_blank">Read more: How to make a multi-player game – part 2</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-80945076205246462532012-11-19T10:50:00.001-08:002012-11-19T10:51:35.246-08:00Quick Tip: The OOP Principle of AbstractionThis entry is part 5 of 5 in the series <a href="http://gamedev.tutsplus.com/series/beginners-guide-to-oop/" title="Beginner's Guide to OOP">Beginner's Guide to OOP</a><br />
We’re almost done with <a href="http://gamedev.tutsplus.com/series/beginners-guide-to-oop/">this series on object-oriented programming</a>, and in this article we’ll discuss the OOP principle of <i>abstraction</i> – that is, generalising an object – and its use in game development.<br />
<b><i>Note:</i></b> <i>Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.</i><br />
<hr /><h2>What is Abstraction?</h2><a href="http://en.wikipedia.org/wiki/Abstraction_principle_(computer_programming)">Abstraction</a> is the principle of generalization. This requires that we move from a specific instance to a more generalized concept by thinking about the most basic information and function of an object.<br />
This may sound a bit strange, but we are already familiar with the concept of abstraction. For example, if I say the word “car”, what do you think of? Odds are we weren’t thinking about the same car. I was thinking about a black <a href="http://www.ford.com/cars/mustang/trim/boss302/">Mustang Boss 302</a>, which is a specific instance of a car. Neither of us were wrong because the word <i>car</i> is a very general concept of a vehicle that we use for transportation (or recreation in my case).<br />
The same goes for video games. Video games are categorized into groups such as RTS, RPG, Racing, etc.. These groups are all generalized concepts that describe the gameplay of a game. <a href="http://en.wikipedia.org/wiki/StarCraft_II:_Wings_of_Liberty">StarCraft II</a>, <a href="http://en.wikipedia.org/wiki/The_Elder_Scrolls_V:_Skyrim">Elder Scrolls V: Skyrim</a>, and <a href="http://en.wikipedia.org/wiki/Need_for_Speed">Need for Speed</a> are all specific instances of these generalized concepts.<br />
Thus, abstraction takes many specific instances of objects and extracts their common information and functions to create a single generalized concept that can be used to describe all the specific instances as one.<br />
<hr /><h2>Why is it Helpful?</h2>Abstraction is helpful because it strips everything down to its most basic principles. This can help when encapsulating functionality of an object because it can help identify the important information that should be made visible and the unimportant information which can be made hidden.<br />
Abstraction also helps with the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don’t Repeat Yourself principle</a>. By taking what a group of objects have in common and abstracting it, we can help prevent redundant code in each object which in turn creates more maintainable code.<br />
<hr /><h2>How to Apply This Principle</h2>As before, let’s use our three games to see some concrete examples of this principle in action.<br />
<h3>Asteroids</h3>[...]<br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-abstraction/" target="_blank">Read more: Quick Tip: The OOP Principle of Abstraction</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-784711222312342358.post-61216244146243967572012-11-15T13:22:00.001-08:002012-11-15T13:22:34.962-08:00Quick Tip: The OOP Principle of EncapsulationThis entry is part 4 of 4 in the series <a href="http://gamedev.tutsplus.com/series/beginners-guide-to-oop/" title="Beginner's Guide to OOP">Beginner's Guide to OOP</a><br />
We’ve discussed <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-intro-to-object-oriented-programming-for-game-development/">object-oriented programming for game developers in general</a> and the specific OOP principles of <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-cohesion/">cohesion</a> and <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-coupling/">coupling</a>. Now let’s take a look at <i>encapsulation</i> and how it helps to keep code loosely coupled and more maintainable. <i><b>Note:</b> Although this Quick Tip is explained using Java, you should be able to use the same techniques and concepts in almost any game development environment.</i> <br />
<hr /><h2>What Is Encapsulation?</h2><a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)">Encapsulation</a> is the principle of information hiding. That is, the <i>implementation</i> (the internal workings) of an object is hidden from the rest of the program. A popular example you’ll hear for encapsulation is driving a car. Do you need to know exactly how every aspect of a car works (engine, carburettor, alternator, and so on)? No – you need to know how to use the steering wheel, brakes, accelerator, and so on. Another example is searching for a value in an array. In Java, you can do the following: <br />
<pre>int myArray[] = {1, 2, 3, 5, 7, 9, 11, 13};
Arrays.asList(myArray).contains(11);
</pre>The above code will return <code>true</code> if the value <code>11</code> is in <code>myArray</code>, otherwise it will return <code>false</code>. How does the <code>contains()</code> method work? Which searching technique does it use? Does it pre-sort the array before searching? The answer is <i>it doesn’t matter</i> because the exact implementation of the method is hidden. <br />
<hr /><h2>Why Is Encapsulation Helpful?</h2>Encapsulation helps to create code that is <a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-coupling/">loosely coupled</a>. Because the details are hidden, it reduces the ability of other objects to directly modify an object’s state and behavior. It also greatly helps when you must change the data type of a variable. Lets say you decided to use a <code>String</code> to keep track of time in “hh:mm:ss” format. After awhile, you come to realize that an <code>int</code> representing seconds might be a better data type for time. Not only must you change the data type in the object, but also every time you referenced the object’s time in the entire program! Instead, you can use what are known as <a href="http://en.wikipedia.org/wiki/Mutator_method">getter and setter</a> functions. Getters and setters are usually small functions that return and set a variable respectively. A getter function to get the time would look as follows: <br />
<pre>public String getTime() {
return time;
}
</pre>The getter will return a <code>String</code> value: the variable <code>time</code>. Now when we want to change <code>time</code> to an int, instead of changing all calls to the getter we can just change the getter function to change the <code>int</code> data type into a <code>String</code> data type. <br />
<a href="http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-the-oop-principle-of-encapsulation/" target="_blank">Read more: Quick Tip: The OOP Principle of Encapsulation</a>Unknownnoreply@blogger.com0