|
How to create real-time games using JavaScript
Is it possible to create actual real-time games using JavaScript? You bet it
is - you can design any kind of game your imagination permits, but if you create
shoot-them-ups you should keep in mind that they will be a little slower compared
to compiled languages such as C++ or C#.
If you prefer games where things are moving, exploding and being shot at, it
is easy to make them in JavaScript provided that you know how to handle various
events as they appear, and the physics affecting the objects in the game.
JavaScript Games are Only the Beginning
JavaScript games along with other types of web-based games can be used to make you real money in ways
you wouldn't expect.
I recommend seeing the
online
video course "How to Make Money from Video Games" to find out how you can make
real money from your games.
Learn How to Make Real Money from Video Games Now
How to move an object on screen
In all shoot-them-up games you control an object - a car, a spaceship, or something
else. In this example, we are using the flying saucer.
Your first task is to make it respond to keyboard events: depending on the
key being pressed, the saucer turns left, right, up or down, or fires a torpedo.
You can use any text editor (even Notepad) to write the JavaScript code, but
you are likely to make lots of mistakes unnecessarily and waste many hours of
your time. To make your scripting a breeze, use Antechinus®
JavaScript Editor , which includes scores of tools to make your life easier:
-
Identify JavaScript elements at a glance with color-coded
syntax
-
Eliminate typing errors and code up to 30 times faster with
Intellisense and auto-complete
-
Eliminate syntax errors: the program finds them, highlights
them and explains them for the speedy correction
-
Eliminate the need to memorize hundreds of functions and their
parameters with context sensitive help
-
Use 2 keystrokes instead of 2,000 with unique type-in
code templates
-
Have you code error free in no time with advanced single-click
debugging with breakpoints and line-by-line program execution:
-
Run the selected piece of JavaScript with one click straight
from the editor for the lightning-fast testing
-
Locate functions in your documents instantly with Function Finder
-
... and a lot more. See
the complete list
How do you capture the the keyboard events to direct the flying saucer where
to move? I'll show you in a second. Learning by example is fast and easy to
understand, so follow these steps:
-
Download the zipped-up source files and
unzip them into a new folder
-
Fire up your JavaScript
Editor and open the game_control.htm file to examine
it.
-
To run the code, click Show Internal Viewer (F5). Alternatively,
click here to run the file online
in your browser.
Let's look at the source code:
<body
onKeyPress="ProcessKeypress(event);">
Every keypress is sent to the ProcessKeypress()
function for further processing:
function ProcessKeypress(e)
{
var
myObj =
"saucer";
var
moveBy =
10;
if
(e.keyCode)
keycode=e.keyCode;
else
keycode=e.which;
ch=String.fromCharCode(keycode);
if(ch=='a')
moveObj(myObj,
-moveBy,
0);
else
if(ch=='s')
moveObj(myObj,
moveBy,
0);
else
if(ch=='w')
moveObj(myObj,
0,
-moveBy);
else
if(ch=='z')
moveObj(myObj,
0,
moveBy);
}
This function moves the flying saucer left when 'a' is pressed,
right when 's' is pressed, up when 'w' is
pressed or down when 'z' is pressed, simply by shifting it
by 10 pixels in the required direction.
If you keep the 'a' key pressed, the saucer continues to move
to the left of the screen. Note that the movement is not very smooth, but rather
jerky.
To move the object in a more natural manner, we need to add acceleration into
the equation.
Velocity and acceleration
-
Use JavaScript Editor to open the acceleration.htm file.
-
To run the code, click Show Internal Viewer (F5). Alternatively,
click here to run the file online
in your browser.
Note that the ProcessKeypress() function now invokes the fireTorpedo()
function when the space key is pressed:
function ProcessKeypress(e)
{
var
myObj =
"saucer";
var
moveBy =
10;
if
(e.keyCode)
keycode=e.keyCode;
else
keycode=e.which;
ch=String.fromCharCode(keycode);
if(ch=='a')
moveObj(myObj,
-moveBy,
0);
else
if(ch=='s')
moveObj(myObj,
moveBy,
0);
else
if(ch=='w')
moveObj(myObj,
0,
-moveBy);
else
if(ch=='z')
moveObj(myObj,
0,
moveBy);
else
if(ch=='
') fireTorpedo(myObj);
}
Before we look into the fireTorpedo() function, here is a
little explanation:
Velocity is swiftness; speed, the rapidity of motion. Mathematically,
it is defined as the rate of change of the position of a body in a specified
direction.
In pseudo-code we can express it like this when we move the object to the right:
While the 's' key is pressed
torpedo.x = torpedo.x + 5
Or, if we want to move the object down:
While the 'z' key is pressed
torpedo.y = torpedo.y + 5
Acceleration is the increase of speed or velocity.
In pseudo-code we can express it like this when we move the object to the right:
While the 's' key is pressed
velocity = velocity + acceleration
torpedo.x = torpedo.x + velocity
Now study the fireTorpedo() and moveTorpedo()
functions. Note that window.setTimeout() is used to invoke
moveTorpedo() recursively and provide the continuous movement.
function fireTorpedo(name)
{
// Get the position of the saucer
var
obj =
document.getElementById(name);
var
px =
parseInt(obj.style.left);
var
py =
parseInt(obj.style.top);
// Fire topredo to the right of the saucer
var
t =
document.getElementById("torpedo");
t.style.left
= px+95;
t.style.top
= py+38;
step
= 0;
accel
= 0.05;
vX=1;
window.setTimeout("moveTorpedo();",
0);
}
function moveTorpedo()
{
step++;
if(step>=steps)
return;
// The effect has finished
// Move torpedo to the right by the given velocity
and acceleration
var
t =
document.getElementById("torpedo");
var
px =
parseInt(t.style.left);
vX+=parseInt(accel);
// Increase velocity by the amount of acceleration
t.style.left
= px
+ vX;
accel+=0.05;
window.setTimeout("moveTorpedo();",
0);
}
As an exercise, modify the code controlling the saucer to include the acceleration.
Gravity and friction
The game_control.htm and acceleration.htm
examples demonstrate how easy it is to get started creating your own games in
JavaScript.
To make your games even more realistic, consider adding gravity
and friction.
Gravity is what makes bodies thrown into the air slow down,
stop, and then fall. To put it simply, gravity is the force of attraction. Two
bodies with equal mass attract each other equally; the body with a bigger mass
attracts the body with a smaller mass.
In pseudo-code:
While the body is falling
velocity = velocity + gravity
body.y = body.y + velocity
Friction is the surface resistance to motion. For example,
in a car-racing game, the friction will be stronger or weaker depending on the
surface you are driving on.
In pseudo-code:
While the body is moving
velocity = velocity - friction
body.x = body.x + velocity
Summary
Use the onKeyPress property of the <body>
tag to capture the keyboard action by the user. Add velocity, acceleration,
gravity and friction into the equasion for creating more realistic games.
Use Flash to make your own real-time game
Learn how you can make your own Flash game in just a few minutes
This guide will show you how to make your own flash
game in AS 2.0 from scratch - with no prior scripting knowledge required.
Adapted from an article on C-Point.com with their permission. No part of this
page can be reproduced on another website without the written permission from
C-Point.com |