Box2D Flash game creation tutorial – part 1

My first Flash game tutorial ever was Flash game creation tutorial – part 1.

It was the first of a series to create a game like jmtb‘s ball games. It was an old AS2 series, and some steps have been ported in AS3 with Create a Flash ball game using AS3.

The “ball” game is so simple yet addictive and customizable that I think it’s the perfect game to start a tutorial series based on a new language.

This time I am not covering a new language but the famous Box2D library, but I am going to add all necessary features to make it an interesting game to play.

In this first chapter, I am going to create the ball and the way you control it, by tapping arrow keys.

I am using the basics of Understanding Box2D applicable forces and Box2D tutorial for the absolute beginners – revamped, which I recommend you to read.

Now this is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class ball01 extends Sprite {
		// world creation
		public var world:b2World=new b2World(new b2Vec2(0,10.0),true);
		public var world_scale:int=30;
		// the player
		public var player:b2Body;
		// force to apply to the player
		public var force:b2Vec2;
		// variables to store whether the keys are pressed or not
		// true = pressed;
		// false = unpressed
		public var left,right,up,down:Boolean=false;
		public function ball01():void {
			// calling thebug draw function
			debug_draw();
			// drawing the boundaries
			draw_box(250,400,500,10,false,"ground");
			draw_box(0,200,10,400,false,"left");
			draw_box(500,200,10,400,false,"right");
			draw_box(250,0,500,10,false,"roof");
			// adding the player at 250,200
			// some listeners
			add_player(250,200);
			addEventListener(Event.ENTER_FRAME, update);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,on_key_down);
			stage.addEventListener(KeyboardEvent.KEY_UP,on_key_up);
		}
		// according to the key pressed, set the proper variable to "true"
		public function on_key_down(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=true;
					break;
				case 38 :
					up=true;
					break;
				case 39 :
					right=true;
					break;
				case 40 :
					down=true;
					break;
			}
		}
		// according to the key released, set the proper variable to "false"
		public function on_key_up(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=false;
					break;
				case 38 :
					up=false;
					break;
				case 39 :
					right=false;
					break;
				case 40 :
					down=false;
					break;
			}
		}
		// simple function to draw a box
		public function draw_box(px,py,w,h,d,ud):void {
			var my_body:b2BodyDef= new b2BodyDef();
			my_body.position.Set(px/world_scale, py/world_scale);
			if (d) {
				my_body.type=b2Body.b2_dynamicBody;
			}
			var my_box:b2PolygonShape = new b2PolygonShape();
			my_box.SetAsBox(w/2/world_scale, h/2/world_scale);
			var my_fixture:b2FixtureDef = new b2FixtureDef();
			my_fixture.shape=my_box;
			var world_body:b2Body=world.CreateBody(my_body);
			world_body.SetUserData(ud);
			world_body.CreateFixture(my_fixture);
		}
		// function to add the player
		public function add_player(px,py):void {
			var my_body:b2BodyDef= new b2BodyDef();
			my_body.position.Set(px/world_scale, py/world_scale);
			my_body.type=b2Body.b2_dynamicBody;
			var my_circle:b2CircleShape=new b2CircleShape(10/world_scale);
			var my_fixture:b2FixtureDef = new b2FixtureDef();
			my_fixture.shape=my_circle;
			player=world.CreateBody(my_body);
			player.CreateFixture(my_fixture);
		}
		// debug draw
		public function debug_draw():void {
			var debug_draw:b2DebugDraw = new b2DebugDraw();
			var debug_sprite:Sprite = new Sprite();
			addChild(debug_sprite);
			debug_draw.SetSprite(debug_sprite);
			debug_draw.SetDrawScale(world_scale);
			debug_draw.SetFlags(b2DebugDraw.e_shapeBit);
			world.SetDebugDraw(debug_draw);
		}
		// functiojn to be executed at every frame
		public function update(e:Event):void {
			// setting the force to null
			force=new b2Vec2(0,0);
			// according to the key(s) pressed, add the proper vector force
			if (left) {
				force.Add(new b2Vec2(-10,0));
			}
			if (right) {
				force.Add(new b2Vec2(10,0));
			}
			if (up) {
				force.Add(new b2Vec2(0,-20));
			}
			if (down) {
				force.Add(new b2Vec2(0,5));
			}
			// if there is any force, then apply it
			if (force.x||force.y) {
				player.ApplyForce(force,player.GetWorldCenter());
			}
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

As you can see, I did not change that much from Understanding Box2D applicable forces and Box2D tutorial for the absolute beginners – revamped.

draw_circle function at lines 19-30 in Box2D tutorial for the absolute beginners – revamped now is called add_player (lines 86-95) and places a circle in the (px,py) coordinates.

The body is named player and is declared in the class at line 14, then is used at line 125 to have the force applied with ApplyForce explained at Understanding Box2D applicable forces.

Notice how different forces are applied according to the arrow key pressed… playing with these values will change the gameplay… which values would you use?

This is the result:

Tap arrow keys to move the ball.

Download the source code.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (15 votes, average: 4.53 out of 5)
Loading ... Loading ...
If you found this post useful, please consider a small donation.
» Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.

13 Responses

  1. Devon says:

    Thanks for yet another amazing tutorial!

  2. Hampe says:

    Hello. When i try to open the fla file with adobe flash cs3 it just says “Unexpected file format”. Do you know why?

  3. Quintus says:

    hey,this is great :D but you didn’t make the ball bounce, I guess it’s named restitution or something like that xD

    yay first

  4. Ljock says:

    @Hampe Maybe the file is in CS4 version, then your cs3 won’t open it.

    I’m also missing the bouncing ball physics, is there a part 2 coming out? :)

  5. Anthony says:

    Great tutorial. But a few quick questions… How do you keep up on what’s been changed with Box2d ??? Also I notice you show how to draw the images in debug mode. How do we actually skin the objects after we are done debugging ??? and can you show where its at in documentations or the API. cause I can not find a list of the api. THANKS and great tutorial!!!!

  6. Guest says:

    Emanuele, i like your tutorials… but lately you start a lot of tutorials but never finish them

  7. styxtwo says:

    “Emanuele, i like your tutorials… but lately you start a lot of tutorials but never finish them”

    this happens to everyone, i beleave emanuele named them vaporware ;).

    nevertheless you shouldn’t count on him to do everything, use his work as a start point and work your own way up. try finishing his tutorial without him saying how its done.

  8. Anthony says:

    he is a she

  9. maro says:

    Hey, why the ball sticks to the ceiling?

  10. Nathan says:

    Hey Emanuele!

    When I test it my screen stays white but shows no errors!

    Do you know what has happened?

  11. [...] seeing the character creation in Box2D Flash game creation tutorial – part 1, it’s time to add some coins to [...]

  12. [...] Feronato has a nice little series on Box2D game creation, and compiled a list of isometric engines for flash game creation. Be sure to check [...]

Leave a Reply