Talking about Actionscript 3, Flash and Game development.
Welcome to the 3rd step of this tutorial.
It’s time to cover walls, or whatever you may call some fixed, deadly obstacles.
Continuing on the OOP lane, the new object called wall has a class coded in a file called wall.as
saved in the same path as the other ones.
This is how we will create a wall object in the main file, as3circle.as
:
package {
import flash.display.Sprite;
import flash.events.Event;
public class as3circle extends Sprite {
public var keyboard_input:keys;
public var circle_hero = new circle;
public var level_wall = new wall;
public var number_of_coins = 4;
public function as3circle() {
for (var i=1; i<=number_of_coins; i++) {
var ingame_coin = new coin;
addChild(ingame_coin);
}
addChild(circle_hero);
var keyboard_sprite = new Sprite();
keyboard_input = new keys(this);
addChild(level_wall);
stage.addEventListener(Event.ENTER_FRAME,on_enter_frame);
}
public function on_enter_frame(event:Event) {
if (keyboard_input.is_left()) {
circle_hero.apply_force(-1,0);
}
if (keyboard_input.is_right()) {
circle_hero.apply_force(1,0);
}
if (keyboard_input.is_up()) {
circle_hero.apply_force(0,-1);
}
if (keyboard_input.is_down()) {
circle_hero.apply_force(0,1);
}
}
}
}
A variable called level_wall
with wall type is created at line 7, then I place the wall object into the game at line 17.
And that's all for the main file. Look how clean it's remaining, despite of all new features I am introducing in the game.
This is the power of classes. Remember.
As for the wall.as
file, here it is, fully commented:
package {
import flash.display.Sprite;
import flash.events.Event;
public class wall extends Sprite {
// variables used in this class
private var point_x:int;
private var point_y:int;
// precision is the number of points I am going to calculate
// on hero's circumference
private var precision:int = 36;
// calculating once for all 2*PI
private var twopi: Number = Math.PI*2;
// main function
public function wall() {
place_wall();
// checking for collisions at every frame
addEventListener(Event.ENTER_FRAME, check_collisions);
}
private function check_collisions(e:Event) {
for (var i=0; i
To check for collisions between the hero and the wall, I am using trigonometry because in this case is a lot more accurate than hitTestObject()
.
You can find the theory behind this method of collision in Create a flash draw game like Line Rider or others - part 2.
And this is the result:
We are closer and closer to a complete game... next time I will cover scoring.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.