Back to "flash Basic Theory Class-Catalog"
Writing code
First, let two small balls move at a certain angle and finally collide with each other. The starting setting is the same as before, with two balls: Ball0 and Ball1. Make them bigger this time, as shown in Figure 11-9, so they have a bigger chance of colliding.
Fig. 11-9 Two dimensional momentum conservation, set stage
Package {
Import Flash.display.Sprite;
Import flash.events.Event;
public class Billiard3 extends Sprite {
private Var Ball0:ball;
private Var Ball1:ball;
private var bounce:number =-1.0;
Public Function Billiard3 () {
Init ();
}
Private Function init (): void {
ball0 = new Ball (150);
Ball0.mass = 2;
ball0.x = stage.stagewidth-200;
Ball0.y = stage.stageheight-200;
BALL0.VX = Math.random () * 10-5;
Ball0.vy = Math.random () * 10-5;
AddChild (ball0);
BALL1 = new Ball (90);
Ball1.mass = 1;
ball1.x = 100;
BALL1.Y = 100;
BALL1.VX = Math.random () * 10-5;
Ball1.vy = Math.random () * 10-5;
AddChild (BALL1);
AddEventListener (Event.enter_frame, onenterframe);
}
Private Function Onenterframe (event:event): void {
ball0.x + = BALL0.VX;
Ball0.y + = Ball0.vy;
ball1.x + = BALL1.VX;
Ball1.y + = Ball1.vy;
Checkwalls (ball0);
Checkwalls (BALL1);
}
Private Function Checkwalls (Ball:ball): void {
if (ball.x + Ball.radius > Stage.stagewidth) {
ball.x = Stage.stagewidth-ball.radius;
BALL.VX *= Bounce;
else if (Ball.x-ball.radius < 0) {
ball.x = Ball.radius;
BALL.VX *= Bounce;
}
if (ball.y + Ball.radius > Stage.stageheight) {
Ball.y = Stage.stageheight-ball.radius;
Ball.vy *= Bounce;
else if (Ball.y-ball.radius < 0) {
Ball.y = Ball.radius;
Ball.vy *= Bounce;
}
}
}
}