Movement

This week, we will be mostly covering...

...Movement and collision detection.
Imagine you want a game with things which move around the screen, and you want to know if and when these things collide. For collision detection, you need to know the position of the two DIVs you are checking, as well as their width and height.
There are two ways of doing this - either declare these values in the style attributes of every DIV tag, or set it up using JS.
To save you having to set up each and every variable, I have developed the sprite object. The sprite object is a custom object, so you will need to include the following line of HTML in your document -
<script language="JavaScript" src="spri.js"></script>
I will make the spri.js file available to all who wish to use it.
To declare a new sprite object, you must have a DIV on your page with an ID. Then, you make a reference to this DIV, like so -
<div id="ship" style="position:absolute; width:50px; height:36px; overflow:hidden;">
<img src="shipani.gif">
</div>
ship=new sprite(50,36,"ship","ww");
Now I will go through the attributes. The first two are the width and height of the DIV. These must be specified in both the HTML and the JS. These values relate to the height and width of the content of the DIV, which is usually an image.
Next is the ID of the DIV the sprite object is connected to.
Finally, the wrapping options. The value of this is always a two character string, each character having one of the following values -
  • l (limit) The sprite stops at the axis limit.
  • w (wrap) The sprite goes off the limit and appears at the other side.
The first character affects the x (horizontal) axis, and the second letter affects the y (vertical) axis.
To make this work, you need to bear the following in mind - the spri.js file uses many global variables. DO NOT use any of the following variables in your own code if you are going to use the spri.js file -
si (Sine array), co (Cosine array), sh (Screen Height), sw (Screen Width)
This week and next will be spent studying the properties and methods of the sprite object.