Sunday, May 23, 2010

This is for you flash people...

I know I'm far from the world's best ActionScript coder, but here's a nugget from something I made a good while back that may be fun to look at and play with. (I know it works in AS2.0, but YMMV with other versions.) Oh yeah, I should mention that it goes on a movieclip.


// Set up initializing parameters.
onClipEvent (load) {
this.stop();
var inertiaX = 0;
var inertiaY = 0;
var angleRad = 0;
thruster_sound = new Sound();
thruster_sound.attachSound("thruster");
}

//Stop sound and thruster animation.
onClipEvent (keyUp) {
this.gotoAndStop(1);
thruster_sound.stop();
}

onClipEvent (enterFrame) {
//Turn left when "A" is pressed.
if (Key.isDown(65) == true) {
this._rotation -= 5;
trace(this._rotation);
}

//Turn right when "D" is pressed.
if (Key.isDown(68) == true) {
this._rotation += 5;
trace(this._rotation);
}

//Convert _rotation to 360deg and radians.
angleDeg = (this._rotation<0)*360+this._rotation;
angleRad = (angleDeg/180)*Math.PI;

//Go forward when "W" is pressed.
if (Key.isDown(87) == true) {
this.play();
thruster_sound.start(0, 2);
inertiaX += Math.sin(angleRad)*.5;
inertiaY -= Math.cos(angleRad)*.5;
trace(angleDeg+" "+angleRad+" "+inertiaX+" "+inertiaY);
}

//Fire shot when "S" is pressed.
if (Key.isDown(83) == true) {
_parent.attachMovie("shot1", "shot1_mc", 10, this);
}

//Keep spacehip on screen by wrapping.
if (this._y<0) {
this._y = 400;
}
if (this._y>400) {
this._y = 0;
}
if (this._x<0) {
this._x = 550;
}
if (this._x>550) {
this._x = 0;
}

//Make spaceship move.
this._x += int(inertiaX);
this._y += int(inertiaY);

//Pass variables to shot fired.
xInit = this._x;
yInit = this._y;

//Check if enemy shot exists.
if (_parent.shot2_mc) {
//Check for enemy shot collision.
if (this.hitTest(_parent.shot2_mc._x, _parent.shot2_mc._y, true)) {
_root.p2Score++;
trace("Hit P2 shot hit P1");
_parent.shot2_mc.removeMovieClip();
}
}
}

No comments: