Back to "flash Basic Theory Class-Catalog"
Catch an Object
The next example is to reuse the Ball class and add it to our engineering or classpath. Then create some new variables for the ball to move. Note that this code is based on the last example and we just need to join:
private var ball:Ball;
private var gravity:Number = 0.5;
private var bounce:Number = -0.9;
In the Init method, create an instance of ball and add the display list.
private function init():void {
ball = new Ball();
ball.vx = 10;
addChild(ball);
segments = new Array();
for (var i:uint = 0; i < numSegments; i++) {
var segment:Segment = new Segment(50, 10);
addChild(segment);
segments.push(segment);
}
segment.x = stage.stageWidth / 2;
segment.y = stage.stageHeight;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
Call a function called Moveball in Onenterframe, just separate the motion code of all the balls, in order to look like it's not confusing:
private function onEnterFrame(event:Event):void {
moveBall();
var target:Point = reach(segments[0], mouseX, mouseY);
for (var i:uint = 1; i < numSegments; i++) {
var segment:Segment = segments[i];
target = reach(segment, target.x, target.y);
}
for (i = numSegments - 1; i > 0; i--) {
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
position(segmentB, segmentA);
}
}
That's the function:
private function moveBall():void {
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
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;
}
}