I am making a top down shooter in flash using AS3 and I'm having some trouble firing a bullet from a ship moved by the WASD keys towards the cursor. The bullets are created fine enough but they go off in random directions rather than towards where the cursor is when you press space.
This is the code for the bullet class:
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Mouse;
import flash.events.MouseEvent;
import flash.geom.Point;
public class Bullet extends MovieClip
{
var speed:Number;
var moveX:Number;
var moveY:Number;
var shipX:Number;
var shipY:Number;
function Bullet(target:Ship)
{
speed = 20;
shipX = target.x;
shipY = target.y;
graphics.lineStyle(7,0x000000);
graphics.moveTo(-2,0);
graphics.lineTo(2,0);
graphics.lineStyle(3,0xffffff);
graphics.moveTo(-2,0);
graphics.lineTo(2,0);
addEventListener(Event.ADDED_TO_STAGE, onStage);
}
function onStage (e:Event)
{
/*addEventListener("enterFrame", enterFrame);
/*var mc =
var angleRadian = Math.atan2(mouseY - mc.y, mouseX - mc.x);
var angleDegree = angleRadian * 180 / Math.PI;
mc.rotation = angleDegree;*/
/*Ship.y += speed * Math.sin((Ship.rotation - 90) * (Math.PI / 180));
Ship.x += speed * Math.cos((Ship.rotation - 90) * (Math.PI / 180));*/
trace(stage.mouseY);
var cy:Number = stage.mouseY - shipY;
var cx:Number = stage.mouseX - shipX;
moveX = cx / cy;
moveY = (cy < 0) ? -1 : 1;
var Radians:Number = Math.atan2(cy,cx);
var Degrees:Number = Radians * 180 / Math.PI;*/
}
function enterFrame(e:Event)
{
/*this.x += speed;*/
this.x += moveX * speed;
this.y += moveY * speed;
if (this.x > 900)
{
removeEventListener("enterFrame",enterFrame);
stage.removeChild(this);
}
if (this.x < 0)
{
removeEventListener("enterFrame",enterFrame);
stage.removeChild(this);
}
if (this.y > 800)
{
removeEventListener("enterFrame",enterFrame);
stage.removeChild(this);
}
if (this.y < 0)
{
removeEventListener("enterFrame",enterFrame);
stage.removeChild(this);
}
for(var i in Enemy.list)
{
if(this.hitTestObject(Enemy.list[i]))
{
removeEventListener("enterFrame", enterFrame);
stage.removeChild(this);
Enemy.list[i].kill();
break;
}
}
}
}
}
Any help getting the bullets to fire properly would be much appreciated!