Game Development Reference
In-Depth Information
The layer behind moves slower than the layer in front; in the following code, look where I'm multiplying
counter by five for the back layer's y position. Remember that counter increments every frame, so our back
layer will move down five pixels per frame.
The front layer moves twice as fast. We use the modulus of the screen height to ensure that when the
position gets too high, it's reset down again. The div images tile vertically, so you don't notice this reset.
This method of moving the front layer faster than the back one gives the illusion of 3D depth, which is
known as
parallax scrolling
.
I tried several different ways of implementing this (including adjusting the background image offset of a static
div), but this method seems the best. Notice that I'm setting the
translateZ
CSS property to 0 in order to
enable 3D rendering, which triggers GPU acceleration, even though I'm not actually moving it in 3D!
Disabling default touch/mouse behavior
Default actions happen on touch events—if you touch and drag, you scroll the web page. On some
devices, a menu appears on a long touch. We need to disable these default actions by calling
event.preventDefault()
.
function fishTouched(event) {
event.preventDefault();
For a production-ready game, we should probably also listen to orientation change events and rescale our
game accordingly, but I wanted to keep this tutorial code as simple as possible.
Getting it on the iPad
It's easy to deploy this game on the web—just stick it on a server and open it on your
iPad browser. You can even use the little forward button in mobile Safari to save it to
your home screen, then it's just like any other app. There's even a meta tag you can add
to your HTML that will make it run in full screen:
<meta name="apple-mobile-web-app-capable" content="yes" />
This is all cool, of course, but sometimes you want a proper app from the App Store—all
official like! Good news—you can wrap up HTML/JS files into apps with PhoneGap
mobile-
application-development
).