This is an introductory tutorial on collision detection and physics. Creating 2D physics is often daunting to the beginner flash programmer but as you will soon see it is really not that hard so long as you break everything down into small steps. Here we are going to create a world and populate it with a realistic bouncing ball:
The concepts required here may look daunting but all that needs to be required are the following:
Velocity
Wall Collision Detection
Friction
Gravity
Defining the world
Lets start off by defining our bounds and our world as a class like so:
Here we start with a World class that contains a backing sprite and a Ball Sprite which we have placed in the middle of the bounds. This tute is all about creating some realistic movement based on basic physics so lets get the ball to move.
Velocity
Within the physical world moving objects have a velocity which represents a distance moved over time. In Actionscript, we have a frame ticker which represents time so once every frame we can add the velocity to the coordinate position of our sprite to give the appearance of movement. Velocity in physics is given as a vector but in Actionscript we can provide it as two separate values for each coordinate. Lets add velocity to our ball:
01
class Ball extends Sprite
02
{
03
public var vx:Number = 0; // velocity x
04
public var vy:Number = 0; // velocity y
05
public var radius:Number = 20; // circle radius
06
07
public function Ball(rad:Number)
08
{
09
// Apply params
10
radius = rad;
11
12
// Draw Ball
13
graphics.lineStyle(1,0xAAAAAA);
14
graphics.beginFill(0xA9C065);
15
graphics.drawCircle(0,0,radius);
16
graphics.endFill();
17
18
// Add Listeners
19
addEventListener(Event.ENTER_FRAME, onFrame);
20
}
21
22
private function onFrame(e:Event):void
23
{
24
// Apply Velocity to Position
25
x += vx;
26
y += vy;
27
28
}
29
}
Notice nothing much has happened. Our Ball is still sitting in the center of the stage and not moving. The reason it isn’t moving is because we have given it an initial velocity of 0 for both the x and y directions. Lets give this a number value of lets say 5. Add the following to our World class:
01
...
02
var ball:Ball;
03
ball = new Ball(20);
04
ball.x = w/2;
05
ball.y = h/2;
06
07
// Initial Velocity
08
ball.vx = 5;
09
ball.vy = 5;
10
...
Which gives us this:
The Flash plugin is required to view this object.
Bingo! the ball is moving but it is hardly realistic. Firstly the ball leaves the bounds almost immediately so we need to provide some collision detection and to constrain it to the given bounds.
Wall Collision Detection
Let’s add the following handler and variable to our Ball class:
01
private var bounds:Rectangle;
02
...
03
public function Ball(rad:Number)
04
{
05
...
06
// Add Listeners
07
addEventListener(Event.ENTER_FRAME, onFrame);
08
addEventListener(Event.ADDED, onAdded);
09
}
10
...
11
private function onAdded(e:Event):void
12
{
13
world = parent as World;
14
bounds = world.bounds;
15
}
This is going to listen for when we add our ball to the world and at that instance get the properties of our world and apply them to the ball animation.
now add the following to our frame routine:
01
private function onFrame(e:Event):void
02
{
03
// Use a temp var for x and y to increase performance
04
var tx:Number = x;
05
var ty:Number = y;
06
07
// Collision Detection with right wall
08
if(tx + vx > bounds.right - radius)
09
{
10
tx = bounds.right - radius;
11
vx *= -1;
12
}
13
14
// Collision Detection with left wall
15
if(tx + vx < bounds.left + radius){
16
tx = bounds.left + radius;
17
vx *= -1;
18
}
19
20
// Collision Detection with floor
21
if(ty + vy > bounds.bottom - radius)
22
{
23
ty = bounds.bottom - radius;
24
vy *= -1;
25
}
26
27
// Collision Detection with ceiling
28
if(ty + vy < bounds.top + radius)
29
{
30
ty = bounds.top + radius;
31
vy *= -1;
32
}
33
34
// Apply Velocity to tx and ty
35
tx += vx;
36
ty += vy;
37
38
// Render the change
39
x = tx;
40
y = ty;
41
42
}
Lastly we need to alter our World class to provide us with the bounds property containing the bounds to constrict the ball to. So lets move our backing instance to become a private instance variable and access its getBounds method for the bounds of the world.
01
class World extends Sprite
02
{
03
...
04
private var backing:Sprite;
05
...
06
public function get bounds():Rectangle
07
{
08
return backing.getBounds(this);
09
}
10
}
Within the frame script we are now checking to see if the object has moved beyond the boundary given by the bounds Rectangle. If the bounds have been exceeded for any given direction the direction is reversed based on the boundary exceeded.
Here we also use a temporary variable to make it so that x is only set at the end of the frame script and is only necessary for performance reasons but is a good habit to get into since it is good to keep data and render separate.
The Flash plugin is required to view this object.
So now we have our ball flying away within our bounding box but the movement doesn’t look particularly real as we haven’t added any of the common physical forces to our object such as friction or gravity.
Adding Friction
To add air friction we simply need to multiply the velocity by a given amount between 0 and 1 every frame ie:
1
// Air Dampening
2
vx *= .99;
3
vy *= .99;
This leaves us with something that looks like the following:
The Flash plugin is required to view this object.
Gravity
The last thing to do is add gravity to simulate the natural pull towards the ground by simply adding to the downward velocity every frame:
01
// Air Dampening
02
vx *= .99;
03
vy *= .99;
04
05
// Gravity
06
vy += 1;
07
08
// Apply Velocity to tx and ty
09
tx += vx;
10
ty += vy;
11
12
// Render the change
13
x = tx;
14
y = ty;
After moving the gravity and friction properties to belong to the World we are left with the following full source code:
Introduction to collision detection & 2D physics
This is an introductory tutorial on collision detection and physics. Creating 2D physics is often daunting to the beginner flash programmer but as you will soon see it is really not that hard so long as you break everything down into small steps. Here we are going to create a world and populate it with a realistic bouncing ball:
The concepts required here may look daunting but all that needs to be required are the following:
Defining the world
Lets start off by defining our bounds and our world as a class like so:
The Flash plugin is required to view this object.
Here we start with a World class that contains a backing sprite and a Ball Sprite which we have placed in the middle of the bounds. This tute is all about creating some realistic movement based on basic physics so lets get the ball to move.
Velocity
Within the physical world moving objects have a velocity which represents a distance moved over time. In Actionscript, we have a frame ticker which represents time so once every frame we can add the velocity to the coordinate position of our sprite to give the appearance of movement. Velocity in physics is given as a vector but in Actionscript we can provide it as two separate values for each coordinate. Lets add velocity to our ball:
Notice nothing much has happened. Our Ball is still sitting in the center of the stage and not moving. The reason it isn’t moving is because we have given it an initial velocity of 0 for both the x and y directions. Lets give this a number value of lets say 5. Add the following to our World class:
Which gives us this:
The Flash plugin is required to view this object.
Bingo! the ball is moving but it is hardly realistic. Firstly the ball leaves the bounds almost immediately so we need to provide some collision detection and to constrain it to the given bounds.
Wall Collision Detection
Let’s add the following handler and variable to our Ball class:
This is going to listen for when we add our ball to the world and at that instance get the properties of our world and apply them to the ball animation.
now add the following to our frame routine:
Lastly we need to alter our World class to provide us with the bounds property containing the bounds to constrict the ball to. So lets move our backing instance to become a private instance variable and access its getBounds method for the bounds of the world.
Within the frame script we are now checking to see if the object has moved beyond the boundary given by the bounds Rectangle. If the bounds have been exceeded for any given direction the direction is reversed based on the boundary exceeded.
Here we also use a temporary variable to make it so that x is only set at the end of the frame script and is only necessary for performance reasons but is a good habit to get into since it is good to keep data and render separate.
The Flash plugin is required to view this object.
So now we have our ball flying away within our bounding box but the movement doesn’t look particularly real as we haven’t added any of the common physical forces to our object such as friction or gravity.
Adding Friction
To add air friction we simply need to multiply the velocity by a given amount between 0 and 1 every frame ie:
This leaves us with something that looks like the following:
The Flash plugin is required to view this object.
Gravity
The last thing to do is add gravity to simulate the natural pull towards the ground by simply adding to the downward velocity every frame:
After moving the gravity and friction properties to belong to the World we are left with the following full source code:
As you can see by adding gravity we substantially increase the reality factor of the motion.
The Flash plugin is required to view this object.