Animate Sprites toward a point - actionscript-3

I'm trying to do something very simple: animate a bunch of sprites so that, no matter where they are on the stage, they all go toward a single point (in this case, the center of the stage).
It only works for some of them. Some of them just sit there. I can't figure out why. I think its got something to do with atan2 and the way I'm using it, but I'm not sure what. Can someone see?
Thanks,
David
package
{
import Ball;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
public class MoveBalls extends Sprite {
private var balls:Array = new Array();
private var speed:Number = new Number(10);
public function MoveBalls() {
init();
}
private function init():void {
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
for(var i:int = 0; i<30; i++)
{
var ball:Ball = new Ball(20);
ball.x = getRandomNumber();
if(ball.x > stage.stageWidth) ball.x = stage.stageWidth -10;
if(ball.x < 0) ball.x = 10;
trace(ball.x);
ball.y = getRandomNumber();
if(ball.y >stage.stageHeight) ball.y = stage.stageHeight - 10;
if(ball.y < 0) ball.y = 10;
addChild(ball);
balls.push(ball);
}
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function getRandomNumber():Number {
var decider:Number = Math.random();
if (decider < 0.5) {
return Math.random()*1000;
} else {
return Math.random()*-1000;
}
}
public function onEnterFrame(event:Event):void {
var targetX:Number = stage.stageWidth/2;
var targetY:Number = stage.stageHeight/2;
for(var i:int=0; i < balls.length; i++)
{
var startX:Number = balls[i].x;
var startY:Number = balls[i].y;
var atanX:Number = (targetX - startX);
var atanY:Number = (targetY - startY);
if(atanX > .1) //just stop when it's close enough to the center
{
var ang:Number = Math.atan2(atanY, atanX);
var xSpeed:Number = Math.cos(ang)*speed;
var ySpeed:Number = Math.sin(ang)*speed;
balls[i].x += xSpeed;
balls[i].y += ySpeed;
}
}
}
}
}
//ball class
package {
import flash.display.Sprite;
public class Ball extends Sprite {
private var radius:Number;
private var color:uint;
public function Ball(radius:Number=40, color:uint=0xff0000) {
this.radius = radius;
this.color = color;
init();
}
public function init():void {
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}
}

I don't agree with this line:
if(atanX > .1)
Because if the balls are to go to the CENTER of the stage, like both on X and Y axes, then this condition fails for balls directly under or above the center.
Make it like this
if (atanX > .1 || atanY > .1)
= If either of the differences are bigger than .1, go on with the atan2...
EDIT:
One more obvious error - the atanX or atanY variables can, in 50% be negative. Therefore, use either this:
if (Math.abs(atanX) > .1 || Math.abs(atanY) > .1)
Or this, which is the same but faster (harder to read, though):
if ((atanX > 0 ? atanX : -atanX) > .1 || (atanY > 0 ? atanY : -atanY) > .1)

Related

State Machine Cant get to work

Learning to code so this might sound noobish...
Using Action Script
I am trying to make my Agents react to my segments so they run away.
So I need to connect part of my Main code to my Agent code
Here is my code :
Main.as
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.display.Stage;
public class Main extends Sprite
{
private var score:Score;
private var count:int;
private var bleh: int = 0;
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 20;
private var player:Point = new Point (200, 200)
private var friend:Agent = new Agent;
private var snakeHead:SnakeHead;
private var snakeTail:SnakeTail;
private var background: Sprite;
private var border: Bushes;
private var xVel: Number;
private var yVel: Number;
public function Main():void
{
xVel = 0;
yVel = 0;
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
snakeHead = new SnakeHead();
snakeTail = new SnakeTail();
score = new Score();
border = new Bushes;
score.x = 11;
score.y = 14;
addChild(score);
stage.addChild(border);
count = 0;
addChildAt(snakeHead,0);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (10, 20);
addChildAt(segment,0);
addChildAt(snakeTail,0);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
background = new LevelOne(); //creates the background
addChildAt(background,0);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 3; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = 400;
a.y = 300;
a.name = "Name"+x;
trace (x);
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(evt:Event):void
{
for (var i:int = 0; i < Agents.length; i++)
{
Agents[i].update();
if (snakeHead.hitTestObject(Agents[i]))
{
//trace (Agents[i].name);
removeAgent(Agents[i]);
Agents.splice(i,1);
count ++;
score.lowercasetext.text = count.toString();
trace("count: " + count);
}
}
}
private function onEnterFrame(evt:Event):void
{
player.x += xVel;
player.y += yVel;
drag(snakeHead, player.x, player.y);
drag(segments[0], snakeHead.x, snakeHead.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
var PlayerHalfWidth: Number = segments[i].width / 2;
var PlayerHalfHeight: Number = segments[i].height / 2;
if (segments[i].x + PlayerHalfWidth > stage.stageWidth) {
segments[i].x = stage.stageWidth - PlayerHalfWidth;
} else if (segments[i].x - PlayerHalfWidth < 0) {
segments[i].x = 0 + PlayerHalfWidth;
}
if (segments[i].y + PlayerHalfHeight > stage.stageHeight) {
segments[i].y = stage.stageHeight - PlayerHalfHeight;
}else if (segments[i].y - PlayerHalfHeight < 0) {
segments[i].y = 0 + PlayerHalfHeight;
}
var playerHalfWidth: Number = segments[i - 1].width / 2;
var playerHalfHeight: Number = segments[i - 1].height / 2;
if (segments[i - 1].x + playerHalfWidth > stage.stageWidth) {
segments[i - 1].x = stage.stageWidth - playerHalfWidth;
} else if (segments[i - 1].x - playerHalfWidth < 0) {
segments[i - 1].x = 0 + playerHalfWidth;
}
if (segments[i - 1].y + playerHalfHeight > stage.stageHeight) {
segments[i - 1].y = stage.stageHeight - playerHalfHeight;
}else if (segments[i - 1].y - playerHalfHeight < 0) {
segments[i - 1].y = 0 + playerHalfHeight;
}
}
drag(snakeTail, segments[19].x, segments[19].y);
var HeadHalfWidth: Number = snakeHead.width / 2;
var HeadHalfHeight: Number = snakeHead.height / 2;
if (snakeHead.x + HeadHalfWidth > stage.stageWidth) {
snakeHead.x = stage.stageWidth - HeadHalfWidth;
} else if (snakeHead.x - HeadHalfWidth < 0) {
snakeHead.x = 0 + HeadHalfWidth;
}
if (snakeHead.y + HeadHalfHeight > stage.stageHeight) {
snakeHead.y = stage.stageHeight - HeadHalfHeight;
}else if (snakeHead.y - HeadHalfHeight < 0) {
snakeHead.y = 0 + HeadHalfHeight;
}
//drag(segments[19], snakeTail.x, snakeTail.y);
/*for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
if(segments[0].hitTestObject(a))
{
trace("True");
trace(bleh + " " + "F*CKING HELL!");
trace(a.name);
stage.removeChild(Agents[1]);
}
}*/
}
private function removeAgent(a:Agent):void
{
a.parent.removeChild(a);
trace("Collision Detected!");
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = -5;
}
if (evt.keyCode == 83)
{
player;
yVel = 5;
}
if (evt.keyCode == 68)
{
player;
xVel = 5;
}
if (evt.keyCode == 65)
{
player;
xVel = -5;
}
//trace (player.x + " " + player.y);
trace (xVel + " " + yVel);
}
private function keyUp (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = 0;
}
else if (evt.keyCode == 83)
{
player;
yVel = 0;
}
else if (evt.keyCode == 68)
{
player;
xVel = 0;
}
else if (evt.keyCode == 65)
{
player;
xVel = 0;
}
}
private function drag(segment:MovieClip, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Agent.as
package agent
{
import agent.states.ChaseState;
import agent.states.ConfusionState;
import agent.states.FleeState;
import agent.states.IAgentState;
import agent.states.IdleState;
import agent.states.WanderState;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.*;
import Segment;
import Main;
public class Agent extends MovieClip
{
private var mouses:mouse;
public static const IDLE:IAgentState = new IdleState(); //Define possible states as static constants
public static const WANDER:IAgentState = new WanderState();
public static const CHASE:IAgentState = new ChaseState();
public static const FLEE:IAgentState = new FleeState();
public static const CONFUSED:IAgentState = new ConfusionState();
public var snake:Segment;
private const RAD_DEG:Number = 180 / Math.PI;
private var _previousState:IAgentState; //The previous executing state
private var _currentState:IAgentState; //The currently executing state
private var _pointer:Shape;
private var _tf:TextField;
public var velocity:Point = new Point();
public var speed:Number = 0;
public var fleeRadius:Number = 100; //If the mouse is "seen" within this radius, we want to flee
public var chaseRadius:Number = 50; //If the mouse is "seen" within this radius, we want to chase
public var numCycles:int = 0; //Number of updates that have executed for the current state. Timing utility.
public function Agent()
{
//Boring stuff here
_tf = new TextField();
_tf.defaultTextFormat = new TextFormat("_sans", 10);
_tf.autoSize = TextFieldAutoSize.LEFT;
_pointer = new Shape();
mouses = new mouse();
snake = new Segment(1, 1);
/*g.beginFill(0);
g.drawCircle(0, 0, 5);
g.endFill();
g.moveTo(0, -5);
g.beginFill(0);
g.lineTo(10, 0);
g.lineTo(0, 5);
g.endFill();*/
addChild(mouses);
addChild(_tf);
_currentState = IDLE; //Set the initial state
}
/**
* Outputs a line of text above the agent's head
* #param str
*/
public function say(str:String):void {
_tf.text = str;
_tf.y = -_tf.height - 2;
}
/**
* Trig utility methods
*/
public function get canSeeMouse():Boolean {
var dot:Number = snake.x * velocity.x + snake.y * velocity.y;
return dot > 0;
}
public function get distanceToMouse():Number {
var dx:Number = x - snake.x;
var dy:Number = y - snake.y;
return Math.sqrt(dx * dx + dy * dy);
}
public function randomDirection():void {
var a:Number = Math.random() * 6.28;
velocity.x = Math.cos(a);
velocity.y = Math.sin(a);
}
public function faceMouse(multiplier:Number = 1):void {
var dx:Number = snake.x - x;
var dy:Number = snake.y - y;
var rad:Number = Math.atan2(dy, dx);
velocity.x = multiplier*Math.cos(rad);
velocity.y = multiplier*Math.sin(rad);
}
/**
* Update the current state, then update the graphics
*/
public function update():void {
if (!_currentState) return; //If there's no behavior, we do nothing
numCycles++;
_currentState.update(this);
x += velocity.x*speed;
y += velocity.y*speed;
if (x + velocity.x > stage.stageWidth || x + velocity.x < 0) {
x = Math.max(0, Math.min(stage.stageWidth, x));
velocity.x *= -1;
}
if (y + velocity.y > stage.stageHeight || y + velocity.y < 0) {
y = Math.max(0, Math.min(stage.stageHeight, y));
velocity.y *= -1;
}
mouses.rotation = RAD_DEG * Math.atan2(velocity.y, velocity.x);
}
public function setState(newState:IAgentState):void {
if (_currentState == newState) return;
if (_currentState) {
_currentState.exit(this);
}
_previousState = _currentState;
_currentState = newState;
_currentState.enter(this);
numCycles = 0;
}
public function get previousState():IAgentState { return _previousState; }
public function get currentState():IAgentState { return _currentState; }
}
}

ArgumentError: Removing Child from Stage

I am trying to develop a basic Snake game that involves some inverse kinematics and state machines. I'm trying to get it so when the first segment of the snake interacts with a certain "mouse", it disappears. However, when I do, it doesn't work and I end up getting ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
Here's my code:
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
public class Main extends Sprite
{
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 150;
private var player:Point = new Point (15, 15)
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (5, 10);
addChild(segment);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
graphics.beginFill(0xeeeeee);
graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 10; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = Math.random() * 10;
a.y = Math.random() * 10;
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
stage.addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(e:Event):void
{
for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
for each(var target: Segment in segments)
{
if (target.hitTestPtarget.x, a.y + target.y, true))
{
stage.removeChild(a);
}
}
}
}
private function onEnterFrame(event:Event):void
{
drag(segments[0], player.x, player.y);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
}
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player.y-=50;
}
else if (evt.keyCode == 83)
{
player.y+=50;
}
else if (evt.keyCode == 68)
{
player.x+=50;
}
else if (evt.keyCode == 65)
{
player.x-=50;
}
trace (player.x + " " + player.y);
}
private function drag(segment:Segment, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
I have tried looking at other posts with the same topic, but I just don't understand what I'm doing wrong. Any help would be greatly appreciated!
You are adding Agents and Segments locally (in Main) and later you are trying to remove them from the stage (which is the top level of the swf and is an another display object).
Either do stage.addChild(...) in your init function or (this is a better option imo) replace stage.removeChild(...) with a removeChild(...) everywhere else - this will keep the objects in a local Main space (who knows, maybe you would want to move around your Main later, make everything invisible at once etc).

Creat Boundaries

Hello Everyone again :) I'm having an issue with boundaries actually about creating boundaries. In my stage I got 2 mc's names : Dispenser and Puller. Dispenser creating particles and puller is pulling them. I just need to set a boundary like a path.
But i couldn't so asking for your help :)
Bdw the code is from this site : http://www.freeactionscript.com/?s=puller&x=0&y=0
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
// you can play around with these
private var particlesTotal:Number = 50;
private var particleSpeed:Number = 10;
private var particleFadeoutSpeed:Number = .0175;
// don't change these
private var particlesCurrent:Number = 0;
private var particlesArray:Array;
private var radians:Number;
private var _sayac:uint;
public function Main():void
{
init();
}
private function init():void
{
radians = 180 / Math.PI;
particlesArray = [];
addEventListener(Event.ENTER_FRAME, onEnterFrameLoop);
dispenser_mc.addEventListener(MouseEvent.MOUSE_DOWN, onThingDown);
puller_mc.addEventListener(MouseEvent.MOUSE_DOWN, onThingDown);
dispenser_mc.addEventListener(MouseEvent.MOUSE_UP, onThingUp);
puller_mc.addEventListener(MouseEvent.MOUSE_UP, onThingUp);
}
private function onThingDown(event:MouseEvent):void
{
event.currentTarget.startDrag();
}
private function onThingUp(event:MouseEvent):void
{
event.currentTarget.stopDrag();
}
private function createParticle(target1:MovieClip, target2:MovieClip):void
{
if(particlesTotal <= particlesCurrent)
{
return;
}
particlesCurrent++;
var tempParticle:Particle = new Particle();
tempParticle.x = (target1.x - target1.width / 2) + (Math.random() * target1.width);
tempParticle.y = (target1.y - target1.height / 2) + (Math.random() * target1.height);
tempParticle.rotation = Math.random()*360;
tempParticle.rot = Math.atan2(target1.y - target2.y, target1.x - target2.x);
tempParticle.xSpeed = Math.cos(tempParticle.rot) * radians / particleSpeed;
tempParticle.ySpeed = Math.sin(tempParticle.rot) * radians / particleSpeed;
tempParticle.mass = tempParticle.width / 2 + tempParticle.height / 2;
particlesArray.push(tempParticle);
addChild(tempParticle);
}
private function updateParticle():void
{
for (var i = 0; i < particlesArray.length; i++)
{
var tempParticle:MovieClip = particlesArray[i];
tempParticle.x -= tempParticle.xSpeed;
tempParticle.y -= tempParticle.ySpeed;
tempParticle.alpha -= particleFadeoutSpeed;
// I know i can set boundries here but idk how to so :)
if(tempParticle.hitTestObject(puller_mc))
{
destroyParticle(tempParticle);
_sayac++;
trace(_sayac);
}
else if (tempParticle.alpha <= 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.x < 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.x > stage.stageWidth)
{
destroyParticle(tempParticle);
}
else if (tempParticle.y < 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.y > stage.stageHeight)
{
destroyParticle(tempParticle);
}
}
}
private function destroyParticle(particle:MovieClip):void
{
for (var i = 0; i < particlesArray.length; i++)
{
var tempParticle:MovieClip = particlesArray[i];
if (tempParticle == particle)
{
particlesCurrent--;
particlesArray.splice(i,1);
removeChild(tempParticle);
}
}
}
private function onEnterFrameLoop(event:Event):void
{
createParticle(dispenser_mc, puller_mc);
updateParticle();
}
}
}
actually there is no boundary in this code. let me explain the main parts of this code for you:
this is the most important part:
tempParticle.rot = Math.atan2(target1.y - target2.y, target1.x - target2.x);
tempParticle.xSpeed = Math.cos(tempParticle.rot) * radians / particleSpeed;
tempParticle.ySpeed = Math.sin(tempParticle.rot) * radians / particleSpeed;
rot is the angle to reach the puller.
xSpeed is how much the particle should go to right  every frame to reach the puller.
ySpeed is how much the particle should go to down every frame to reach the puller.
and in updateParticle function, the partcle will move, according to xSpeed and ySpeed.
so the correct xSpeed and YSpeed will cause particles to go straight.not a boundary !
I   h ☻ p e   I explained good and ,
I   h ☺ p e   this helps !

AS3 game character only shoots in one direction

I'm making a top down shooter game and so far my character can move and can shoot when mouse is click. But it will only shoot to the right and not where my cursor is pointing. How do i fix this?
Here's the bullet code in the main class:
public var bulletList:Array = [];
stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
public function shootBullet(e:MouseEvent):void
{
var bullet:Bullet = new Bullet(stage, harold.x, harold.y, harold.rotation);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true);
bulletList.push(bullet);
stage.addChild(bullet);
}
public function loop(e:Event):void
{
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved);
bulletList.splice(bulletList.indexOf(e.currentTarget),1);
}
Here is the code in my Bullet Class:
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage;
private var speed:Number = 10;
private var xVel:Number = 0;
private var yVel:Number = 0;
private var rotationInRadians = 0;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
}
public function loop():void
{
xVel = Math.cos(rotationInRadians) * speed;
yVel = Math.sin(rotationInRadians) * speed;
x += xVel;
y += yVel;
if(x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
this.parent.removeChild(this);
}
}
}
}
A few thoughts:
As said by Aaron, you should compute rotationInRadians in the constructor, altought the real formula is this.rotationInRadians = rotationInDegrees * (Math.PI / 180);
You should make rotationInRadians a number, that is private var rotationInRadians:Number;
Are you aware displayObject has a getter/setter for rotation? In other words: harold.rotation is a property in harold object or is it referencing to said getter?
I think thats pretty much it.
I think you forgot to assign rotationInRadians in your constructor:
this.rotationInRadians = rotationInDegrees * (Math.PI / 180);
BTW, unless you want the bullet to be able to change direction during flight, you don't need to calculate the xVel and yVel each loop(), you can just calculate it in the constructor, store it, then update the x and y each loop().

All my references to the stage method are throwing null reference errors in as3

I'm not sure what the change was that caused this, but suddenly i'm getting null object references in all the cases that I use the stage method as a parameter. My code is too long to fit all the different instances, so I'll just attach one or two.
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class Main extends MovieClip
{
public var ourPlanet:Cosmo = new Cosmo(stage);
public var ourAsteroid:Asteroid = new Asteroid();
private var numStars:int = 80;
private var numAsteroids:int = 5;
public static var a:Number = 0;
private var stageRef:Stage;
//public var ourAsteroid:Asteroid = new Asteroid(stage);
//private var ourAsteroid:Asteroid = new Asteroid();
//our constructor function. This runs when an object of
//the class is created
public function Main()
{
//create an object of our ship from the Ship class
stop();
//add it to the display list
stage.addChild(ourPlanet);
ourPlanet.x = stage.stageWidth / 2;
ourPlanet.y = stage.stageHeight / 2;
this.stageRef = stageRef;
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), stage.getChildIndex(ourPlanet));
}
for (var o:int = 0; o < numAsteroids; o++)
{
stage.addChildAt(new Asteroid(), stage.getChildIndex(ourPlanet));
}
My debugger tells me there is a null object reference at line 13, and this code is from my engine. Cosmo is another external file that is linked to a symbol. I'll post the code from there, but there are about 4 of these errors across 4 different .as files, but it'd be too much code to put in here, so I'll just add from one other file I think would be important.
Code From Cosmo.as
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import com.senocular.utils.KeyObject;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.text.TextField;
public class Cosmo extends MovieClip
{
private var stageRef:Stage;
private var key:KeyObject;
private var speed:Number = 20;
private var vx:Number = 0;
private var vy:Number = 0;
private var friction:Number = 0.93;
private var maxspeed:Number = 8;
public var destroyed:Boolean = false;
public function Cosmo(stageRef:Stage)
{
this.stageRef = stageRef;
var key:KeyObject = new KeyObject(stage);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
public function loop(e:Event) : void
{
//keypresses
if (key.isDown(Keyboard.A))
vx -= speed;
else if (key.isDown(Keyboard.D))
vx += speed;
else
vx *= friction;
if (key.isDown(Keyboard.W))
vy -= speed;
else if (key.isDown(Keyboard.S))
vy += speed;
else
vy *= friction;
//update position
x += vx;
y += vy;
//speed adjustment
if (vx > maxspeed)
vx = maxspeed;
else if (vx < -maxspeed)
vx = -maxspeed;
if (vy > maxspeed)
vy = maxspeed;
else if (vy < -maxspeed)
vy = -maxspeed;
//ship appearance
rotation = vx;
scaleX = (maxspeed - Math.abs(vx))/(maxspeed* 4) + 0.75;
//stay inside screen
if (x > stageRef.stageWidth)
{
x = stageRef.stageWidth;
vx = -vx;
}
else if (x < 0)
{
x = 0;
vx = -vx;
}
if (y > stageRef.stageHeight)
{
y = stageRef.stageHeight;
vy = -vy;
}
else if (y < 0)
{
y = 0;
vy = -vy;
}
}
}
}
I'm also getting an error here at line 26 for the same thing.
Code from another file
package com.senocular.utils {
import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* The KeyObject class recreates functionality of
* Key.isDown of ActionScript 1 and 2
*
* Usage:
* var key:KeyObject = new KeyObject(stage);
* if (key.isDown(key.LEFT)) { ... }
*/
dynamic public class KeyObject extends Proxy {
private static var stage:Stage;
private static var keysDown:Object;
public function KeyObject(stage:Stage) {
construct(stage);
}
public function construct(stage:Stage):void {
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
flash_proxy override function getProperty(name:*):* {
return (name in Keyboard) ? Keyboard[name] : -1;
}
public function isDown(keyCode:uint):Boolean {
return Boolean(keyCode in keysDown);
}
public function deconstruct():void {
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
keysDown = new Object();
KeyObject.stage = null;
}
private function keyPressed(evt:KeyboardEvent):void {
keysDown[evt.keyCode] = true;
}
private function keyReleased(evt:KeyboardEvent):void {
delete keysDown[evt.keyCode];
}
}
}
In this file, i'm getting errors at lines 23 and 29. Thanks in advance, let me know if you need more information of any kind.
The stage property is going to be null until added to the display list hierarchy of the stage. You can't add the object to the stage until after the constructor is executed, so therefore you won't ever be able to access stage in the constructor. It's going to be null.
Call the construct method after creating the instance and adding it to the stage's display list hierarchy.