Back to "flash Basic Theory Class-Catalog"
Optimizing Code
We've seen some examples of code optimizations earlier. This is usually done in lieu of multiple executions, or simply not executed.
The piece of code we wrote earlier is just to see it clearly. Some of these codes do not actually need to be executed. Most code executes only if the ball is in contact with line. Therefore, most of the time requires only the execution of basic motion code. In other words, we're going to put the code in the IF statement:
if(y2 > -ball.height / 2)
So we just need to know the variable y2. In order to get it needs x1 and Y1 as well as sin and Cos. But if ball doesn't touch line, you don't need to know X2 or vx1 and vy1. Therefore, these can only appear in the IF statement. Similarly, if there is no collision, there is no need to rotate or set the ball position of any object. Therefore, the content behind all if statements can be executed in the IF statement. So we get the optimized version of the Onenterframe method (see ANGLEBOUNCEOPT.AS):
Private Function Onenterframe (event:event): void {
Normal motion Code
Ball.vy + = gravity;
Ball.x + = BALL.VX;
Ball.y + = Ball.vy;
Gain angle and positive cosine value
var angle:number = line.rotation * MATH.PI/180;
var cos:number = Math.Cos (angle);
var sin:number = Math.sin (angle);
Get the relative position of ball and line
var x1:number = ball.x-line.x;
var y1:number = ball.y-line.y;
Rotation coordinates
var y2:number = cos * y1-sin * x1;
Achieve rebound
if (y2 >-ball.height/2) {
Rotation coordinates
var x2:number = cos * x1 + sin * y1;
Rotational velocity vector
var vx1:number = cos * BALL.VX + sin * ball.vy;
var vy1:number = cos * ball.vy-sin * BALL.VX;
y2 =-BALL.HEIGHT/2;
Vy1 *= Bounce;
Spin it all back.
x1 = cos * x2-sin * y2;
y1 = cos * y2 + sin * x2;
BALL.VX = cos * vx1-sin * VY1;
ball.vy = cos * vy1 + sin * vx1;
ball.x = line.x + x1;
BALL.Y = line.y + y1;
}
}
All of the bold content is moved out of the IF statement, so they are executed only when collisions occur, which is much better than executing each frame. Can you imagine how much CPU resources we have saved? Such considerations are very important, especially when the movie becomes more and more complex and the code becomes more and more complicated.
Dynamic effects
Now we can make this program more dynamic and change the line angle in real time. Only one line of code is required to be done, and the first line of the Onenterframe method is written:
line.rotation = (stage.stageWidth/ 2 - mouseX) * .1;
Now, as soon as we move the mouse back and forth, line will tilt and the ball will adjust immediately. Complete code-visible document class anglebouncerotate.as.