Game Development Reference
In-Depth Information
planning to simulate a galaxy, you will need to treat stars, or even clusters of stars as particles. If you are
simulating rain, your particles will be individual raindrops.
In this chapter, I will show you how to design and implement your own particle effects using HTML5 canvas.
We will gradually build up the code by adding the features we need to implement and improve the effects.
Please note that the code in this chapter is optimized to be simple and easy to understand. It should serve
as an example of the mechanisms involved in a particle system. It does not always reflect best practices
for production code. For example, the code does not use any namespaces or a module system, which is a
must for any complex application. The examples shown are very high-fidelity and may need to be scaled-
down to fit into the resource budget of a game.
Math
To create a particle system, you will need some basic math. The good thing about coding creative
systems, however, is that you can't go wrong. If it looks good, it is good. So feel free to try out all your
crazy ideas, even if they are “wrong,” they might end up looking surprisingly good.
Vectors
To animate particles, some simple linear algebra is required. The most important concept for that is clearly
the vector. A vector can describe a point in space, like the location of our particle. But it can also describe
a direction and distance in space; for example, the speed and direction of a particle. If you are already
familiar with vectors, you can safely skip this section.
A vector is defined by an n-tuple of numbers. As we will be operating in 2D space, our vector will have two
components: x and y.
We will use the default coordinate system of canvas. So for a point, x denotes the distance from the left in
pixels; and y is the distance from the top. For a velocity, x is the number of pixels the point will travel to the
right in one second; and y denotes the number of pixels it will move down.
If you are building a game, it often makes sense to use SI units. For simplicity, we will stick to pixels and
seconds as the units in this chapter.
function Vec2(x, y){
this.x = x;
thix.y = y;
}
We can now use Vec2 to define a basic particle.
function Particle(position, velocity){
this.position = position;
this.velocity = velocity;
}
Let's go through an example to see how those vectors work in practice:
 
Search WWH ::




Custom Search