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 >>> |
Create a Ball Movie Clip, and draw a squared "ball":

Then place this Movie Clip anywhere you want inside the main timeline with the name "Ball". Open the actions for the ball and paste:
onClipEvent(load)
{
//On load we set a random x and y for the ball
_x = (Math.random() * 80) + 10;
_y = (Math.random() * 180) + 10;
//random direction; 0 = left, 1= right.
dir = Math.round(Math.random() * 1);
//speed of the ball
speed = 10;
if (dir == 1)
{
//if going right, Ang will be 45
var Ang = 45;
} else {
//if going left, Ang will be 135
var Ang = 135;
}
//x vector for the ang, how much to move in the x coordinate
xspeed = speed * Math.cos((Ang) * Math.PI / 180);
//y vector, how much to move on the y coordinate.
yspeed = speed * Math.sin((Ang) * Math.PI / 180);
}
onClipEvent(enterFrame)
{
//if we hit the border Movie Clip
if (_root.Limits.Border.hitTest(this._x + xspeed, this._y + yspeed, true))
{
//change direction of movement in the x coordinate, the ball will bounce.
xspeed = -xspeed;
}
//if we hit one of the pads
if (_root.Limits.Pads.hitTest(this._x + xspeed, this._y + yspeed, true))
{
//change the direction on the y coordinate.
yspeed = -yspeed;
}
//move the ball in the predetermined speed;
this._x += xspeed;
this._y += yspeed;
//if the player didn't catch the ball we do the same thing we did on load to reset the ball
if (this._y > 200)
{
_x = (Math.random() * 80) + 10;
_y = (Math.random() * 180) + 10;
dir = Math.round(Math.random() * 1);
speed = 10;
if (dir == 1)
{
var Ang = 45;
} else {
var Ang = 135;
}
xspeed = speed * Math.cos((Ang) * Math.PI / 180);
yspeed = speed * Math.sin((Ang) * Math.PI / 180);
} else if (this._y < 0) {
//if the opponent didn't catch the ball we do the same thing
//as before, only difference is in the angle
_x = (Math.random() * 80) + 10;
_y = (Math.random() * 180) + 10;
dir = Math.round(Math.random() * 1);
speed = 10;
if (dir == 1)
{
// so it goes up and right
var Ang = -45;
} else {
//up and left.
var Ang = 225;
}
xspeed = speed * Math.cos((Ang) * Math.PI / 180);
yspeed = speed * Math.sin((Ang) * Math.PI / 180);
}
}
More cool tech articles from other blogs.
| Index Series | Next >>> |
