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.
Actionscript (as2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | //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; } } |
Here is the gravity.fla to download and play with.
Tags: actionscript, as2, experiment, flash, interactive, open source





















Leave a Reply