Game Development Reference
In-Depth Information
For clouds, you do something slightly more complicated. You want the clouds to move from left
to right or vice versa, and if a cloud disappears from the screen, you want a new one to appear.
To do this, you add a Clouds class to the game. You create an instance of this class in the Level
constructor and assign it a higher layer value than the background itself and the mountains. This
ensures that the clouds are drawn in front of the mountains:
var clouds = new Clouds(ID.layer_background_3);
backgrounds.add(clouds);
Because the Clouds class contains a number of moving clouds, it's a subclass of the GameObjectList
class. In the constructor, you use a for instruction to create a number of clouds and add them to the
list. Each cloud is given a random position and a random x velocity. Take a look at the constructor of
the Clouds class in the TickTickFinal example to see how this is done.
The Clouds class also has an update method, in which you check whether a cloud has exited the
screen. Because you need to do this for each cloud game object, you use a for instruction to
traverse all the cloud objects in the list. If a cloud has exited the screen, you create a new cloud
object with a random position and velocity. A cloud can exit the screen either on the left side or on
the right side. If a cloud is positioned outside of the screen on the left , and its x velocity is negative ,
you know it has exited the screen. This is also true if the cloud is positioned outside of the screen
on the right side, and its velocity is positive . You can capture these two cases for a cloud c in the
following if instruction:
if ((c.velocity.x < 0 && c.position.x + c.width < 0) ||
(c.velocity.x > 0 && c.position.x > powerupjs.Game.size.x)) {
// remove this cloud and add a new one
}
Removing the cloud is easy:
this.remove(c);
Then you create a new cloud game object:
var cloud = new powerupjs.SpriteGameObject(sprites["cloud_" + Math.ceil(Math.random()*5)]);
You assign an x velocity to this cloud, which can be either positive or negative. The y velocity of the
cloud is always zero so the cloud only moves horizontally:
cloud.velocity = new powerupjs.Vector2(((Math.random() * 2) - 1) * 20, 0);
Note in this instruction that you calculate a random number between -1 and 1 and then multiply
that number by 20. This allows you to randomly create clouds with either a positive or a negative
x velocity. You calculate a random cloud y position by multiplying the screen height by a random
number between zero and one. From that number, you subtract half of the cloud height to make sure
you never generate a cloud that is drawn fully below the screen:
var cloudHeight = Math.random() * powerupjs.Game.size.y - cloud.height / 2;
Search WWH ::




Custom Search