Movement w/ Boundaries
This is a pretty straightforward tutorial. It covers simple movement and boundaries, which are commonly used in overhead-style games. (think GTA or GTA2). I'm not very good with actionscript, so forgive me if there's a better way to do it. I pretty much learned everything I know about boundries from Rystic's Platformer Tutorial. In fact, this tutorial is pretty much a modified version of his. All credit should go to him. So let's begin.
Here are a sample file:
SAMPLE (arrow keys - move)
Tutorial:
Draw a square and make it a movie clip. No need to give it an instance name, the code will do it for you. (another thing I learned from Rystic's tutorial). Open up the actions menu, and put in this code:
onClipEvent (load) {
_name = "guy";
speed = 5;
}
onClipEvent (enterFrame) {
xmin = getBounds(_root).xMin;
xmax = getBounds(_root).xMax;
ymin = getBounds(_root).yMin;
ymax = getBounds(_root).yMax;
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.LEFT)) {
_x -= speed;
}
if (Key.isDown(Key.RIGHT)) {
_x += speed;
}
if (Key.isDown(Key.UP)) {
_y -= speed;
}
if (Key.isDown(Key.DOWN)) {
_y += speed;
}
}
The speed variable can be changed to whatever you want. So can the keys. The movement is pretty straightforward. UP makes the Y value decrease, DOWN makes it increase, same for the X value with LEFT and RIGHT. The xmin = getBounds(_root).xMin; lines get the boundaries of the object and turn them into easy-to-use variables. Hooray variables.
Alrighty. Now make another square. This will be your wall. Put this code in it:
onClipEvent (enterFrame) {
xmin = getBounds(_root).xMin;
xmax = getBounds(_root).xMax;
ymin = getBounds(_root).yMin;
ymax = getBounds(_root).yMax;
if (hitTest(_root.guy) && _root.guy.xmax<xmin) {
_root.guy._x -= _root.guy.speed;
}
if (hitTest(_root.guy) && _root.guy.xmin>xmax) {
_root.guy._x += _root.guy.speed;
}
if (hitTest(_root.guy) && _root.guy.ymin<ymax) {
_root.guy._y -= _root.guy.speed;
}
if (hitTest(_root.guy) && _root.guy.ymin>ymax) {
_root.guy._y += _root.guy.speed;
}
}
There's the code for the walls and whatnot. They don't need instance names, so go nuts. But what does this code do? Well, I'll try my best to explain. The first part is the same as before. It converts the boundaries into easy-to-use variables. The second part tells the guy to stop when he hits a wall.
if (hitTest(_root.guy) && _root.guy.ymin>ymax) {
_root.guy._y += _root.guy.speed;
}
When the guy hits the wall, the wall takes the guy's speed in that direction and adds negative to it. Because (something) + (negative something) = 0, it effectively stops it.
There you have it. I think.
Speaking of Maine, how bout that Rhode Island? Rhode Island is neither a road, nor an island. Discuss.