Gravity

A variation of the gravity with throwable ball experiment. It has optional gravity.

Click the ball to drag and release to drop or throw it.
Press the space bar to add more balls (up to 30).
Press the down arrow to turn gravity off, and pres the up arrow to turn it back on.

You can make some pretty interesting movements. The source fla file is at the bottom of the post. I learned most of this from Keith Peter’s gravity tutorial.

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2007/03/gravity07.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript (as2)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//global variables initialized in frame 1
gravity=2;
drag=.99;
bounce=.8;
_root.id = 1;

//on the ball
onClipEvent (load) {
//random placement
this._x = random(Stage.width);
this._y = random(Stage.height);
//random x and y speed
this.xspeed = Math.random() * 30;
this.yspeed = Math.random() * 30;
//give this ball an id
this.ballNum = _root.id;
//increment id until 30 and then reset
if (_root.id < 30) {
_root.id++;
}
else {
_root.id = 2;
}
}
//drag ball on press
on (press) {
startDrag(this);
this.dragging = true;
}
//create new ball with space bar
on (keyPress “<Space>”) {
if (this.ballNum == 1) {
duplicateMovieClip(_root.ball, “ball” + _root.id, _root.id);
}
}
//toggle gravity with up and down arrow
on (keyPress “<Down>”) {
_root.gravity = 0;
}
on (keyPress “<Up>”) {
_root.gravity = 2;
}
//drop on release
on (release, releaseOutside) {
stopDrag();
this.dragging = false;
}
onClipEvent (enterFrame) {
//if not dragging
if (!this.dragging) {
//calculate new x and y position
this._y = this._y + this.yspeed;
this._x = this._x + this.xspeed;
//bounce off the bottom of stage and reverse yspeed
if (this._y + this._height / 2 > Stage.height) {
this._y = Stage.height – this._height / 2;
this.yspeed = -this.yspeed * _root.bounce;
}
//bounce off the top of stage and reverse yspeed
if (this._y – this._height / 2 < 0) {
this._y = this._height / 2;
this.yspeed = -this.yspeed * _root.bounce;
}
//bounce off right of stage
if (this._x + this._width / 2 > Stage.width) {
this._x = Stage.width – this._width / 2;
this.xspeed = -this.xspeed * _root.bounce;
}
//bounce off left of stage
if (this._x – this._width / 2 < 0) {
this._x = this._width / 2;
this.xspeed = -this.xspeed * _root.bounce;
}
//recalculate x and y speeds figuring in drag (friction) and gravity for y
this.yspeed = this.yspeed * _root.drag + _root.gravity;
this.xspeed = this.xspeed * _root.drag;
}
else {
//if dragging then calculate new speeds according to dragging movement and speed
this.xspeed = this._x – this.oldx;
this.yspeed = this._y – this.oldy;
this.oldx = this._x;
this.oldy = this._y;
}
}
[/cc]

Here is the gravity.fla to download and play with.