package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
[SWF(width=465, height=465, frameRate=30, backgroundColor=0xFFFFFF)]
/**
* Simple canon.
* @author makc
* @license WTFPLv2, http://sam.zoy.org/wtfpl/
*/
public class Cannon extends Sprite
{
public function Cannon ()
{
stage.addEventListener (Event.ENTER_FRAME, loop);
stage.addEventListener (MouseEvent.CLICK, fire);
}
// origin
private var o:Point = new Point (465 / 2, 350);
// acceleration (gravity)
private var a:Point = new Point (0, 0.1);
// bullets
public var bullets:Array = [];
public function loop (e:Event):void
{
// draw ground
graphics.clear ();
graphics.lineStyle ();
graphics.beginFill (0xA0FFA0);
graphics.drawRect (0, o.y, 465, 465 - o.y);
// direction from origin to mouse
var d:Point = new Point (mouseX, Math.min (o.y, mouseY)).subtract (o);
// normalize it to gun length
d.normalize (25);
// draw the gun and aim line
graphics.lineStyle (5, 0);
graphics.moveTo (o.x, o.y); graphics.lineTo (o.x + d.x, o.y + d.y);
graphics.lineStyle (0, 0xA0FFA0);
graphics.lineTo (mouseX, Math.min (o.y, mouseY));
for each (var b:Bullet in bullets)
{
// draw the bullet
graphics.lineStyle ();
graphics.beginFill (0xFF0000);
graphics.drawCircle (b.p.x, b.p.y, 2);
// if it's not on the ground yet
if (b.p.y < o.y) {
// apply velocity
b.p = b.p.add (b.v);
// apply gravity
b.v = b.v.add (a);
// stop once we hit the ground
b.p.y = Math.min (o.y, b.p.y);
}
}
}
public function fire (e:MouseEvent):void {
// make new Bullet
var b:Bullet = new Bullet;
// init velocity with direction to mouse
b.v = new Point (mouseX, Math.min (o.y, mouseY)).subtract (o);
// scale velocity vector for reasonably small speed
b.v.x *= 0.02;
b.v.y *= 0.02;
// position: we start where the gun ends
b.p = b.v.clone (); b.p.normalize (25); b.p = b.p.add (o);
// put the bullet on our list
bullets.push (b);
}
}
}
import flash.geom.Point;
class Bullet {
// position
public var p:Point;
// velocity
public var v:Point;
}