Friday 6 February 2009

Flash - Walls

How to create walls to use with movieclips using very simple ActionScript.

1. Open Flash and create a New Document.

2. Use the Rectangle Tool (R) and draw out a square (50x50 pixels).

3. Select it using the Selection Tool (V) and then Convert it to a Symbol (F8). Name it "square", make it a MovieClip and the Registration centred. Now, with the square selected, open up the Properties panel and give it an Instance Name of "square".

4. Next, open up the Actions panel (F9) and enter the following ActionScript:
onClipEvent(enterFrame){
if(Key.isDown(Key.RIGHT)){
this._x += 10;
}
if(Key.isDown(Key.LEFT)){
this._x -= 10;
}
if(Key.isDown(Key.UP)){
this._y -= 10;
}
if(Key.isDown(Key.DOWN)){
this._y += 10;
}
}

Explanation

if(Key.isDown(Key.RIGHT)){ - if the Right Arrow key is pressed
this._x += 10; - move the square 10 pixels to the right
._x + - ...is the horizontal axis, so if you move along the x-axis in a positive direction, you move to the right
._y - - the y-axis is different on Flash (don't ask why!) so if you move along the y-axis in a negative direction, you move upwards and vise versa.

5. Now you need to create the walls. You can use any kind of shape for this but it much simpler to use lines. Select the Line Tool (N) and draw out a square. You could also use the Rectangle Tool to draw the square and then delete the fill.

6. You now need to make each wall a MovieClip. First select the top wall and hit F8 to convert it to a symbol. Name it "WallTop", leave the Type as MovieClip and the Registration as centred. Do the same for "WallBottom", "WallLeft" and "WallRight".

7. Enter the following Actionscript to each individual wall:
WallTop
onClipEvent(enterFrame){
if(this.hitTest(_root.square)){
_root.p1._y += 10;
}
}

WallBottom
onClipEvent(enterFrame){
if(this.hitTest(_root.square)){
_root.p1._y -= 10;
}
}

WallLeft
onClipEvent(enterFrame){
if(this.hitTest(_root.square)){
_root.p1._x += 10;
}
}

WallRight
onClipEvent(enterFrame){
if(this.hitTest(_root.square)){
_root.p1._x -= 10;
}
}

Explanation

if(this.hitTest(_root.square)){ - if the square touches 'this', the top wall in this case
_root.p1._y += 10; - move the square down 10 pixels
This works because the wall is pushing the square away at the same rate that the square is moving. If you were to increase the speed of the square to 11, it would slowly, but eventually, move through the wall. So if you plan to change the speed of the square, make sure you also change the value of the wall's pushing force.

8. Test your movie (Ctrl+Enter).

If you want the walls to be invisible just change the colour to match the background.
Have fun!

No comments:

Post a Comment