Ping Pong - Ball Movement
| Category | : Flash | Views | : 40084 | ||
| Version | : 8 | Rating | : | ||
| Type | : Text | Source File | : ping-pong-ball-movement.zip | ||
| Result | : See the result | ||||
| Index Series | Next >>> |
Code Explanation
onClipEvent(load)
{
_x = (Math.random() * 80) + 10;
_y = (Math.random() * 180) + 10;
dir = Math.round(Math.random() * 1);
In the first two lines we set the position of the Ball Movie Clip to a random location, then we get a random value of 0 or 1 for the "dir" variable that will determinate the direction of the Ball (0 = left, 1= right).To get the random value for the "dir" variable we use two functions:
Math.round(floating-point) and Math.random()
The random function returns a floating-point between 0 and 1 so we need to round it up or down using the round function.
speed = 10;
Set the speed to 10px per frame.
if (dir == 1)
{
var Ang = 45;
} else {
var Ang = 135;
}
Here we choose the angle that the Ball will move; if it is supposed to move to the right it needs to move at an angle of 45, if the Ball is to move to the left the angle needs to be 135.
xspeed = speed * Math.cos((Ang) * Math.PI / 180);
yspeed = speed * Math.sin((Ang) * Math.PI / 180);
}

This is vector math; it's the value of 10px at 45コ or 135コ for the _x and _y coordinates.
onClipEvent(enterFrame)
{
if (_root.Limits.Border.hitTest(this._x + xspeed, this._y + yspeed, true))
{
xspeed = -xspeed;
}
Check if the Ball will hit the Border after moving, if it will hit we make the Ball bounce by making its new xspeed the opposite of the current xspeed.We only change the "xspeed" because the Ball needs to continue to move up or down but needs to change direction horizontally.
if (_root.Limits.Pads.hitTest(this._x + xspeed, this._y + yspeed, true))
{
yspeed = -yspeed;
}
Check if the Ball will hit the Pads after moving, if it will hit we make the Ball bounce by making its new yspeed the opposite of the current yspeed.Here we change the yspeed, to make the ball change direction vertically.
More cool tech articles from other blogs.
| Index Series | Next >>> |
