Simplifying JavaScript game developer’s life… PART II
In the second part of dhtml game developing tutorial I want to present simple and very effective sprite animation technique. The Background positioning. 1. You need to have an image that contains all animation frames of your sprite.
- All frames should have the same size.
- Put the frames in a suitable sequence.First frame: Mario stands,
Mario first, second, third step in right
Mario first, second, third step in left. - The start position of the next frame should be the end position of the last frame.For example:First frame position: (0,y)Second frame position: (0+width,y) Third frame position: ((0+width)*2,y) So the main formula will be: n- frame number (width*(n-1),y) Your frame have 32px width and you need the position of the fourth frame (32*3,y) = (96,y) Remember this work only when all frames have the same width.
- Save your image as a GIF or PNG format. The JPEG is recommended for large images. Do not use BMP format.
2. Create a layer with the width of the one frame:
position: absolute; // we’ll use left, top, right, bottom properties,
width: 32px; // only one frame will be visible,
height: 64px; // the height of frame,
left: 0; top: 0; // place it wherever you want,
background-image: url(mario.gif); // path to our image,
background-position: 0 0; // This is important, pointing at the first frame.
3. Animation: Now, we need to change/move the frame:
background-position: -(width*(n-1)) 0; so, which frame do you want? fourth? ok (32*(4-1))*(-1)= -96 background-position: -96px 0;
Why we multiply by -1? Fourth frame starts at 96px, but we see only frame at position 0, so we need to move the image 96px left. Rule is simple: Plus - when we need to move right, Minus - when we need to move left. Here is a simple demonstration of this technique in action, also I’m using collision detection and getValue functions described in the previous part of this tutorial…
Background positioning demo - Mario
CSS background-position Property
Web
Blog
News
Video
Wiki