How to Limit Movement of a Windows Games Sprite

How to Limit Movement of a Windows Games Sprite

How to Limit Movement of a Windows Games Sprite

One of the most important things about creating an animation (for instance in an on-line game) is not how to start an animation but how to stop it. Take, for example, some simple code that uses some object oriented programming to move an image across the screen of an Internet Explorer web browser:

If this code is saved into a .html file (for example “animation.html”) and viewed in Internet Explorer then an image (“alien.png” as shown in figure 1 at the bottom of this article) will be seen to move from left to right across the screen. However, there is a problem. The image does not stop moving. It will move across the background image and off the right side of the screen. The progress of the image’s journey can then be mapped by the increasing size of the scroll bar at the bottom of the screen.

Limiting the Movement of a Game Sprite

Obviously the movement of the game sprite must be limited to the games area. The programmer could do this by hard coding the dimensions of the games area into the application, or a neater way to do it is to to ensure that a sprite can only move within the bounds set by the background image.

Limiting the Movement of a Game Sprite to the Bounds of a Background Image

The properties of the background image can be used to limit the extend to which the foreground image can travel. This “maximum x” value can be calculated from:

the left value of the background image’s style
the width value of the background image
And, of course the width of the image itself must be taken into account:

Private Function max_left
Dim bg_left: bg_left = replace(,”px”,””)
max_left = cint(bg_left) + background.width – Sprite.width
End Function
The programmer can now modify the”move_x” subroutine, using the function above to provide the limit of the image’s movement to the right:

Public Sub move_x
If (next_left <= max_left) Then = next_left
End If
End Sub
If the web page is reloaded at this point then the image of the alien will be seen to move across screen, from left right, and then to stop at the edge of the background image (as shown if figure 2). The programmer can then move on to create similar functionality for movement down the y axis.