Sprite Module (last update 27/05/04)

Description:

This module is responsible for creating and manipulating sprites. If you wish to use sprites in your game/animation, you must link this module in.

The sprite module is optimised to use "canvas animation". This means that all the animation frames for a sprite are in the same image. This equates to faster download times, and much faster animation! For gamelib, "frames" (which incorporate "animations") are in the horizontal axis, and animations in the vertical. You can see a canvas which has 11 frames, with 2 animations in each here. All the animation cells in a canvas must be of the same size.

To use:

The code can be linked in to your script by adding this line to the <HEAD> section of your document:

<script language="Javascript" src="gamelib_sprites.js"></script>

IMPORTANT NEW PROPERTY - PLEASE READ: Due to the continuing rendering problems with Mozilla under Linux/Mac platforms, I've decided to add a new global variable to the gamelib until it's resolved. If you wish to enable linux compatible mode, add the following statement to your script before creating any sprites:

Sp_linuxcompatible=true;

This will enable a work-around for the broken Mozilla rendering engine. "Why not just add it all the time?" I hear you ask ;-) Well, enabling that work-around has the unfortunate side effect of disabling the sprite scaling method for reasons I won't bore you with here. So in short, if you don't need to scale sprites, you may as well enable the workaround so your game works on more browsers!

A new sprite is created via the following technique:

mySprite=new Sp_Sprite();

List of methods for sprites

clearCollisionArea
clearFrameByDirection
clearRoute
clearRouteLoop
destroy
dragType
follow
getHits
getXYdegs
groupHit
groupSet
hasHit
makeDraggable
makeHard
makeNormal
makeStatic
makeUndraggable
moveTo
resize
setAnimation
setAnimationLoop
setAnimationRepeat
setAnimationSpeed
setCollide
setCollisionArea
setCollisionZTest
setDir
setFalling
setFallingSpeed
setFinishPos
setFrame
setFrameByDirection
setHardHitEvent
setHitEvent
setImage
setJumping
setJumpSpeed
setOpacity
setRoute
setRouteByCommand
setShootDelay
setSpeed
setValue
setXlimits
setXYdegs
setYlimits
setZ
stopFollowing
stopTargetting
swapImage
switchOn
switchOff
target
useHitEvents

List of properties for sprites

animdir
animpos
animspd
beingfollowed
bounces
collides
draggable
falling
fallingSpeed
finishPos
followedby
following
followingx
followingy
frame
group
hard
height
hit
hitevents
image
jumping
jumpSpeed
isstatic
on
onclickdown
onclickup
onmouseout
onmouseover
opacity
shootDelay
speed
state
width
value
x
xdir
xmin
xmax
xydegs
y
ydir
ymin
ymax
z

List of Global functions for sprite library

Sp_groupClearTrigger
Sp_groupGetMembers
Sp_groupReset
Sp_groupSetTrigger

List of Global properties for sprite library

Sp_linuxcompatible
Sp_xoffset
Sp_yoffset
Sp_totalsprites
Sp_spritesonscreen

Descriptions of methods

Method Parameters Description
clearCollisionArea (none) Removes the collision area from a sprite. The sprite will register collisions around its perimeter (the default behaviour). See the setCollisionArea() method for details about setting collision areas.
clearFrameByDirection (none) Stops sprite from setting its own frame based on its current direction. See the setFrameByDirection() method for details about this.
clearRoute (none) This stops sprite from following a route. See setRoute() method for details of how to set a route.
clearRouteLoop (none) This stops the sprite from looping through a route. It will continue following its current route until the end. See the setRoute() method for details about setting a route.
destroy (none) This will "destroy" the sprite object. After calling this method, the sprite will no longer respond to any methods. In actuality, the sprite object still exists, and is reused the next time a new sprite is generated. The reason the destroy method does not actually destroy the sprite (IE, remove all the properties, methods and DOM objects from the document) is to work around the memory leak in IE6 (and possibly IE5), whereby the browser never actually frees up any memory allocated when a DOM object is generated, when that object is destroyed (unless the browser is minimized and maximized again for some bizarre reason!)
setCollisionArea Numeric, Numeric, Numeric, Numeric Sets the collision area for a sprite. This is a rectangular region within the sprite which should be used to register collisions. Any collisions outside this area will be ignored (think of it as a "soft" area outside the collision area). Basically this means that you can cause sprites to overlap slightly before a collision will occur which is handy with oddly shaped sprites. The parameters passed are the distances from the left, right, top and bottom (in that order) of the sprite for the collision area rectangle. Setting this will not affect performance. See the clearCollisionArea() method for details about clearing collision areas.
setCollisionZTest Numeric Sets the maximum distance another sprite can be within in the Z axis to be able to collide with this sprite (see the setZ method for details of how to set the Z index). Eg, If this sprite has a Z index of 10 and you use mySprite.setCollisionZTest(5) then other sprites with a Z index less than 5 or higher than 15 will not be able to collide with it! This can be a very useful setting and may help to speed up your code if used correctly since the Z test is performed before the normal collision test and is very quick. So, if you don't care whether certain sprites collide, just set this value so collisions will be ignored!
setRoute Boolean, Numeric, Numeric [...] (or Array) This sets a route for the sprite to follow. This method can be passed an array OR a list of arguments to specify the route. If an array were used, it would contain exactly the same elements that would be passed in the list and so I will describe the list method here.

The first argument specifies whether the sprite should loop (true means loop, false means don't) through the route until cleared (using clearRoute()). After the first argument, any number of numeric x,y values can follow this, which specify the co-ordinates the sprite should visit during the route.
setRouteByCommand String, Boolean This programs a sprite with a set of commands, in order to create a complex route. The first argument is a string containing the commands, separated by semi-colons. Any white space is ignored. The second argument specifies whether the sprite should loop (true means loop, false means don't) through the route until cleared (using clearRoute()). The commands a sprite understands are all of the form of a character, followed by either one or two arguments, separated by a comma. The commands follow:

mX,Y; will move the sprite to position X,Y on the screen. So m100,50; will move the sprite to position 100,50.

aX,Y; will move turn the sprite anticlockwise by Y degrees per frame for X frames. So a20,2; will move the sprite 2 degrees anticlockwise per frame, for 20 frames.

cX,Y; will move turn the sprite clockwise by Y degrees per frame for X frames. So c20,2; will move the sprite 2 degrees clockwise per frame, for 20 frames.

sX; will set the sprite's speed to X.

dX; will set the sprite's direction to X degrees (0-359).

fX; will move the sprite forward at its current speed for X frames.

AX; turn the sprite anticlockwise by X degrees.

CX; turn the sprite clockwise by X degrees.

To see an example of the setRouteByCommand in action, take a look at Sprite example 3.
getHits (none) This will return an array containing references to all the sprites this sprite hit during the last gameloop. If it didn't hit anything, this array will be empty. It's probably more efficient to test for a hit first by checking the .hit property, which always holds the last sprite hit during the last gameloop. If nothing was hit, .hit will be false.
hasHit Object Use this to test if the sprite has hit another. This superseeds the old hit property. So if this sprite is called fred and you want to know if it has hit a sprite called bill, just use

if(fred.hasHit(bill)){
 //do something
}

* Note: In most circumstances, the setHitEvent() method for sprites is probably an easier way of handling collisions - since the sprites will then call functions as soon as they've hit a target instead of you having to check!
makeStatic (none) This makes sprite static. See isstatic property
makeNormal (none) This makes sprite normal
moveTo Numeric, Numeric This moves sprite to position on screen. * Note: this is relative to the global offsets, unless the sprite is static, and sprite will only appear if it's property "on" is true or it's static
setDir Numeric, Numeric This sets sprite directions. These are added to the sprite positions every loop by the sprite engine
setXlimits Numeric, Numeric This limits the sprite x movement. sprite cannot move left further than the first argument, or right further than second argument minus its width. If property "bounces" is true then sprite will bounce when it hits its limit
setYlimits Numeric, Numeric This limits the sprite y movement. sprite cannot move up further than the first argument, or down further than second argument minus its height. If property "bounces" is true then sprite will bounce when it hits its limit
setImage String, Numeric, Numeric, Numeric, Numeric

* Note: DO NOT use this method for normal image .src changes if the new image will have the same dimensions, instead use the swapImage() method, which is MUCH faster for this!

sets the sprite image. Sprite images can be in "canvas animation" format, this is a method of animating sprites that radically decreases download times, and incurs almost no CPU overhead. The image will consist of all the frames of animation for the sprite. frames (see setFrame() below) are in x axis, and animations (set setAnimation(), setAnimationSpeed()) are in y axis for each frame.

The arguments to this method are passed in the following order:
img = the image src (eg "mypicture.gif") x = width of the frames (frames are the different shapes for the sprite) y = height of the frames x2 = number of frames in image y2 = number of animations per frame

"frames" are in the X axis of a canvas image and "animations" are in the Y axis. (See example of sprite animation for clarification on this)

swapImage String Swaps the sprite's image to a new passed as the argument. You must use setImage() to set the sprite's initial image. This method will not resize the image currently in use, and so should only be used to swap between images of the same size unless you don't mind the scaling. On the other hand though, it's very fast!
setFrame Numeric This sets the sprite's frame. Each frame can have a number of animations. Using this resets the animation position for a sprite to the first animation for the frame (animation position 0). You must set a frame for a sprite before it will be displayed at all. If a sprite only has one frame, and no animation, use setFrame(0)
setFrameByDirection Numeric, Numeric, Numeric [...] This method is used to specify which frames the sprite should use when it's heading in different directions. The arguments are in sets of 3, and are of the form degree,degree,frame, degree,degree,frame etc etc. So if you wanted a sprite to use frame 0 when it was moving in the direction between 50 and 70 degrees, and frame 1 when it was moving between 71 and 100 degrees, you could use something like this:

mySprite.setFrameByDirection(50,70,0,71,100,1);

Easy huh? :-) You can specify up to 360 degrees for a sprite's frames. Sprites are intelligent enough to translate between degrees and absolute directions too, so if you set the direction to (1,-1), the sprite knows to use the frame that covers 45 degrees!
setFalling Numeric

You can use this in any way you feel appropriate. Perhaps set to 1 if the sprite is falling, then 0 if the sprite is not falling. For example:

mySprite.setFalling(1);

setFallingSpeed Numeric

This is another useful property. You can use this to keep a record of the sprite's falling speed.

mySprite.setFallingSpeed(8);

Note: At this time there are no falling functions provided in the sprite module. You will have to handle this yourself. FallingSpeed, setFalling, setJumpSpeed etc are simply properties that you can use in whatever way you choose.

setFinishPos Numeric

It is often useful to calculate a finish position for a sprite when it is falling.

mySprite.setFinishPos(278);

setJumping  

You can use this in any way you feel appropriate. Perhaps set to 1 if the sprite is jumping, then 0 if the sprite is not jumping. For example:

mySprite.setJumping(1);

setJumpSpeed  

This is another useful property. You can use this to keep a record of the sprite's jumping speed. You can change it in your script if you want to make the sprite's jump speed slow down to 0 to make it look realistic. Perhaps once it reaches 0 you can setJumping(0), then setFalling(1) and define a fallingSpeed (see above).

mySprite.setFallingSpeed(8);

setAnimation Numeric This sets the sprite's animation stage for the frame
setAnimationLoop Numeric, Numeric

This sets the animation limits for a frame between the first and second arguments. This is used when using a canvas image with animations of varying lengths (for example, 2 stages of animation for one frame, 5 for another frame etc)

You cannot set the animation limits below 0, or above the maximum amount of animations specified when canvas was loaded into the sprite using setImage(). Also, the first argument cannot be greater than the second. The method checks for these things and adjusts the values to correct limits. This is useful if you wish to revert to the default animation limits for a sprite, just set the first argument to 0 and the second to a large number!

setAnimationRepeat Numeric When this is set to a value above -1, the sprite will animate x times. A value of -1 means "keep animating indefinately". Once the sprite stops animating, you can start it animating again by either using this method again, or using the setAnimationSpeed() method
setAnimationSpeed Numeric [,String]

The first argument sets the sprites animation speed. A value of 0 means no animation. Any other value means how many frames between animation changes. So 1 would mean every frame, 2 would mean every other frame etc. When animating, the sprite keeps the same frame but loops through the animations for that frame (between the default limits of animation when the setImage() method was called, or the limits imposed by setAnimationLoop()). 0 is the default speed for animations (no animation).

The optional second argument is either "forward" or "backward" (case insensitive). "forward" means loop through animation stages from top to bottom of the image you gave the sprite, "backward" loops up from bottom to top. "forward" is the default setting. If this argument is omitted, the sprite will continue to animate in its current direction.

setShootDelay Numeric A useful property. The gamelib engine doesn't do anything with this. You can use it in whatever way you wish. A suggestion is to use it in shooting games. Only let a sprite fire if it's shoot delay is <0. Then set the sprite's shoot delay to, say, 5 when it shoots. On every loop reduce the sprite's shoot delay e.g mySprite.setShootDelay(mySprite.shootDelay-1).
setSpeed Numeric Sets the sprite speed
getXYdegs (none) This method will return the sprite's current direction as degrees of a circle. So if you had set the direction to (1,0) for example, this method would return 90. The return value is always an integer between 0 and 359.
setValue Numeric This sets the sprite's value. See the value property for details.
setXYdegs Numeric This sets the sprite direction between 0 and 359 degrees. wraps so that 360 degs=0, 370 degs=10 etc
setZ Numeric This sets the sprite z-index. Sprites with higher values move over those with lower ones
switchOn (none) This switches the sprite on. When a sprite is created, it is off by default, and so not visible
switchOff (none) This switches the sprite off (default)
resize Numeric, Numeric

This resizes the sprite to x,y size. Note: this is not the size of the canvas, but the size of the individual frames/animations in the canvas. Any collision area settings are retained. Be aware that Netscape 4 has difficulties resizing images, so although it will work, there will be some flickering if sprites are being resized constantly.

dragType Numeric/String

Defines how the sprite can be dragged (see makeDraggable() method which must be used first). The dragType can be one of the following:

0 or "normal" =normal dragging (default).
1 or "vertical" =Sprite can only be dragged in the y axis.
2 or "horizontal" =Sprite can only be dragged in the x axis.

* Note: sprites cannot be dragged outside their x and y limits (xmin,xmax,ymin,ymax)

follow Sprite Object, Numeric, Numeric As with the layer object (see layer docs), this causes the sprite to follow another sprite or the mouse object, remaining at distance x,y (where x is the second argument, y the third) from the object it's following. A sprite can only follow one object at a time, so you MUST use the stopFollowing() method before you make a sprite follow something else!
groupHit (none) This will cause a groupHit event for this sprite's group. If the group this sprite belongs to has a trigger set, and this hit, added to the current total of hits in the group has reached the group's trigger value, then the group's trigger event will fire, and the groups hit count will be reset to zero. (see global group functions section for more details about sprite groups)
groupSet Numeric This will add the sprite to a group. If a group with the ID passed as the parameter does not exist, it will be created and the hitCount for the group set to zero. (see global group functions section for more details about sprite groups)
makeDraggable (none) Makes the sprite draggable! * Note: You must have the mouse module linked in to use this
makeUndraggable (none) Stops the sprite from being draggable! * Note: You must have the mouse module linked in to use this
setCollide Boolean If true, the sprite will register collisions. If this is false, then the hit events will not work (default=false)
stopFollowing (none) Calling this method causes the sprite to stop following another sprite or the mouse
useHitEvents Boolean If true, then sprite will use hit events (and hard hit events) as defined below. Using these events does not have much impact upon performance, and can greatly simplify your own code! Don't enable them unless you're actually going to use them though...
setHitEvent Sprite Object,String String argument is function name (usually, but can be any legitimate javascript statement) to be called when this sprite hits the Sprite Object. You cannot set a hit event for the mouse since there are already 4 mouse events for that!
target Sprite Object, Numeric, Numeric The sprite will now move toward the Sprite Object, offset from its top left corner by x,y pixels (passed as the second and third arguments. Whether it catches a moving sprite or not depends on the speeds of the two sprites. A sprite can only target one object at a time, so use the stopTargetting() method before you make a sprite target a new object.
stopTargetting String This stops the sprite from targetting another sprite. If the String 'drift' is passed (ie mySprite.stopTargetting('drift')) then the sprite will continue moving in the direction it was before it stopped targetting.
makeHard (none) This makes sprite hard (fnaa fnaa :). See hard property for details
setHardHitEvent String The string argument is a function (usually, but can be any legitimate javascript statement) to be called when this sprite hits ANY hard sprite. You must enable hit events for the sprite to use this (see useHitEvents() method)
setOpacity Numeric Sets the opacity of the sprite. Range is from 0 to 100, with 0 being invisible. It's probably not a good idea to use this too much in a game, as it affects performance when there are a lot of semi-transparent objects flying around (looks nice though!) This function has no effect with Netscape 4 (browser does not support transparency.)

Descriptions of properties

Property Data Type Read/Write Description
on Boolean R Use this to determine whether the sprite is on/off. When off, it's not on screen.
state Numeric? R/W Not currently used by gamelib. Can be used for anything!
value Numeric R Sprite's value. This has no effect on the sprite engine itself. It was added as a convenience property. If for instance your player blows up a sprite called "alien", we can use something like score+=alien.value. Set the value with the setValue method.
x Numeric R Sprite's X position (see also Sp_xoffset)
y Numeric R Sprite's Y position (see also Sp_yoffset)
z Numeric R Sprite's z position. Sprites with higher value will pass over sprites with lower, also if a sprite collides with more than one other during a loop, the sprite with the highest z index will be reported in the hit property.
xmin Numeric R The minumum allowed x position for sprite. Sprite will either stop or bounce (see bounces) if it hits this limit.
ymin Numeric R The minimum allowed y position for sprite. Sprite will either stop or bounce (see bounces) if it hits this limit.
xmax Numeric R The maximum allowed x position for sprite. Sprite will either stop or bounce (see bounces) if it hits this limit.
ymax Numeric R The maximum allowed y position for sprite. Sprite will either stop or bounce (see bounces) if it hits this limit.
bounces Boolean R/W If sprite hits boundary this decides whether it bounces or stops.
width Numeric R The width of sprite
height Numeric R The height of sprite
xdir Numeric R The direction of sprite in x axis
ydir Numeric R The direction of sprite in y axis
xydegs Numeric R The current direction of sprite as 0-359 degrees
speed Numeric R The speed of sprite. the x and y directions are multiplied by this figure
collides Boolean R/W This decides whether the sprite should check for a collision each loop. Note: If this sprite collides with more than one other sprite during a loop, the sprite with the highest z value will be returned in the hit property. You can and should now set this property using setCollide() detailed in the method section
hard Boolean R If a sprite is hard, other sprites that detect collisions will not be able to pass through it unless they are moving so quickly that they "jump" the hard sprite. The other sprite will register a collision, and be stopped at the point at which it was about to pass through the hard sprite. If the other sprite is not moving, the hard sprite will push it along. The hard sprite itself will generally act like any other sprite apart from its hardness. Hard sprites are ideal as walls/barriers/platforms in a game!
frame Numeric R The current frame being used by an animated sprite. Use setFrame() to change.
animpos Numeric R The current animation position for a frame. Use setAnimation() to change.
animdir String R The direction of animation, either "forward" or "backward". Use setAnimationType() to change
animspd Numeric R The number of frames between animation changes. 0 means no animation. Use setAnimationSpeed() to change
hit Object R If not null, the object it holds is the last sprite this sprite has collided with. collides must be set to true for this to work. * Note: This property is deprecated. Please use the hasHit() method or create hit events instead of this, which can report multiple collisions.
falling Numeric   This is used to signify that the sprite is falling. I usually set to 1 if falling, 0 otherwise.
fallingSpeed     This can be used to store a falling speed for a sprite. This is handy if you want to increase a sprite's speed as it falls to simulate gravity.
finishPos     This is the sprite's finish position which you can use to tell it when to stop falling.
image String R The image canvas the sprite is using. Its dimensions must be (width*frames) wide and (height*animations) of the sprite shape.
isstatic Boolean R Whether sprite is static. If static, sprite does not detect or cause collisions, does not have speed, dirrection or move relative to global positions. These are ideally used for screen elements that are not part of the gameplay (lives left displays, timers, bonus displays, non-moving backgrounds etc). It can only be moved by moveTo(x,y)
jumping     This has the same purpose as falling (see above).
shootDelay Numeric   Contains the sprite's shoot delay. See setShootDelay for more info.
jumpSpeed     This has the same purpose as fallingSpeed (see above). But for jumping of course :)
onmouseover String R/W The string is the function name to be called when the mouse pointer has moved over the sprite. This CAN include arguments so mySprite.onmouseover="dosomething(x,y,z)" would pass the variables x,y,z to the function dosomething
onmouseout String R/W The string is the function name to be called when the mouse pointer has moved away from the sprite
onclickdown String R/W The string is the function name to be called when the mouse button has been pressed while over the sprite
onclickup String R/W The string is the function name to be called when the mouse button has been released while over the sprite
draggable Boolean R/W Whether the sprite is draggable or not. You should now use the new makeDraggable() and makeUndraggable() methods rather than setting this "by hand". See also dragType() method. Note: sprites cannot be dragged outside their x and y limits (xmin,xmax,ymin,ymax)
hitevents Boolean R Whether this sprite is using hit events (see setHitEvent() method
beingfollowed Boolean R True if sprite is being followed by another object (sprite or layer)
followedby (array of Objects) R Which objects are following this sprite (see follow() method)
following Object R The sprite this sprite is following
followingx Numeric R The x offset to sprite this sprite is following
followingy Numeric R The y offset to sprite this sprite is following
opacity Numeric R The opacity level of sprite (0-100) Using opacity will obviously impact performance

Descriptions of Global functions for sprite library

FunctionParametersDescription
Sp_groupClearTriggerNumeric This will clear the trigger for the group passed as the parameter to this function. See the Sp_groupSetTrigger function for details about group triggers.
Sp_groupGetMembersNumeric This will return an array of references to all the sprites that belong to the group passed as the parameter to the function. If there are no members, the array will be empty.
Sp_groupResetNumeric This will reset the trigger counter for the group passed as the parameter to this function. See the Sp_groupSetTrigger function for details about group triggers.
Sp_groupSetTriggerNumeric, Numeric, String This will set a trigger for a group. The parameters to pass to this function are the groupID, then the number of sprite groupHits that will cause the group to trigger, and finally a string containing the function or instructions to execute when the trigger value is reached. When used properly, groups and group triggers can be very powerful tools. The most obvious use is to create Boss type sprites which comprise of many sprites all working together. A hit on any one of the sprites will affect the group, and by using the Sp_groupGetMembers function, you can easily control a whole group of sprites as one entity if you wish!

Descriptions of Global properties for sprite library

PropertyData TypeRead/WriteDescription
Sp_linuxcompatible BooleanR/W If this is set to true, linux compatibility mode is enabled for the sprite engine. Setting this to true will enable a workaround to a bug in the Mozilla rendering engine (at the time of writing, the most recent version of Mozilla is 1.1).
Sp_xoffsetNumericR/W (default=0) The origin of the sprites in the x axis. A sprite x position is relative to this unless the sprite is static. This variable is also the x origin for the mouse object (see mouse docs)
Sp_yoffsetNumericR/W (default=0) the origin of the sprites in the y axis. A sprite y position is relative to this unless the sprite is static. This variable is also the y origin for the mouse object (see mouse docs)
Sp_totalspritesNumericRThe number of sprites you've created
Sp_spritesonscreenNumericR The number of sprites currently on screen. This does not include static sprites