Moving sprites in a tile-based environment
[ July 18, 2003 ] by Marco Lapi, a.k.a Lapo
In this tutorial, two different prototypes illustrate how to move your sprites within a tile-based maze using a two dimensional array for detecting obstacles.




click in the movie, then use arrow keys to control the green square.

Download the source code of this example

MOVING THE SPRITE

Based on the article published last month, we will go one step further by adding a user movable sprite.
The green square represents our sprite and we will use the map Array() to check if it can be moved in the direction requested.

First some initialization code:

_root.attachMovie("item","sprite",10000)
sprite._x = 40
sprite._y = 20
sprite.px = 2
sprite.py = 1
		    

Pretty simple! The movie clip is attached from the library and placed on the stage. Then we setup the two
coordinate systems... why two? Because we use Array positions to know where we are and we also use pixel positions to physically move the sprite. So px and py represent our in-the-Array location.

The next piece of code is a function that is executed every frame and it simply checks which directionkey is pressed and it processes the request accordingly:

sprite.onEnterFrame = function()
{
	if ((Key.isDown(Key.LEFT)) && (map[this.py][this.px-1] != 1))
	{
		this.px--
		this._x -= 20
	}
	if ((Key.isDown(Key.RIGHT)) && (map[this.py][this.px+1] != 1))
	{
		this.px++
		this._x += 20
	}
	else if ((Key.isDown(Key.UP)) && (map[this.py-1][this.px] != 1))
	{
		this.py--
		this._y -= 20
	}
	else if ((Key.isDown(Key.DOWN)) && (map[this.py+1][this.px] != 1))
	{
		this.py++
		this._y += 20
	}
}


Each directional move is performed only if a blank tile is present in the chosen direction, making our sprite walk in the maze without traversing walls.

(continues on page 2)


     
 
 
Name: Marco Lapi, a.k.a Lapo
Location: Fossano, Italy
Age: 34
Flash experience: started out with Flash 4 back in 1999
Job: web designer/developer
Website: http://www.gotoandplay.it/
 
 
| Homepage | News | Games | Articles | Multiplayer Central | Reviews | Spotlight | Forums | Info | Links | Contact us | Advertise | Credits |

| www.smartfoxserver.com | www.gotoandplay.biz | www.openspace-engine.com |

gotoAndPlay() v 3.0.0 -- (c)2003-2008 gotoAndPlay() Team -- P.IVA 03121770048