Actionscript 3 error 1009: Cannot access a property or method of a null object reference - actionscript-3

I'm trying to make a simple game on Animate CC. Everything seems to work fine except when I look in the output, I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
at _2D_CW2_Game_v10_8_fla::MainTimeline/move()
at _2D_CW2_Game_v10_8_fla::MainTimeline/updateOb()
So I know where the issue might be, and I've been trying tweaking the code for days, googling possible solutions, but to no avail...
My entire source code is as below. Any feedback/suggestions will be greatly appreciated.
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundMixer;
//==================================================
// Variable declaration
//==================================================
// defines the variables for boundaries
var left:Number = 0;
var top:Number = 0;
var right:Number = stage.stageWidth;
var bottom:Number = stage.stageHeight;
var velX:Number = 0;
var velY:Number = 0;
var gravity:Number = 1;
var friction:Number = 0.8;
var bounce:Number = -0.5;
var score:Number = 2;
var cv:Number = 0;
var curCount:Number = 30; // countdown 30s
var rightKeyDown:Boolean = false;
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var touchGround:Boolean = false;
// create and place player object on stage
var player:Player = new Player();
player.x = 110;
player.y = 460;
addChild(player);
// create obstacle array
var obstacles:Array = new Array();
var numOb:Number = 3;
// create and place enemies on stage
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = new Npc();
ob.x = 800;
ob.y = 470;
ob.scaleX = -1;
ob.vx = Math.random() * 20 + 1;
addChild(ob);
obstacles.push(ob);
}
//==================================================
// Event handlers
//==================================================
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
addEventListener(Event.ENTER_FRAME, updateOb);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
//==================================================
// Functions
//==================================================
function keyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = true;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = true;
}
if (e.keyCode == Keyboard.UP) {
// if player isn't already jumping and is on the ground
if (!upKeyDown && touchGround) {
// then start jumping
isJumping();
}
upKeyDown = true;
}
}
function keyUp(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = false;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = false;
}
if (e.keyCode == Keyboard.UP) {
upKeyDown = false;
}
}
function EntFrame(e:Event):void {
player.x += velX;
player.y += velY;
velX *= friction;
velY += gravity;
if (player.y >= 450) {
touchGround = true;
player.y = 450;
}
// boundary checks
if (player.x + player.width/2 > right) {
player.x = right - player.width/2;
player.velX *= bounce;
} else if (player.x - player.width/2 < left) {
player.x = left + player.width/2;
player.velX *= bounce;
}
// make player move left or right
controls();
if (curCount > 0) {
cv++;
if (cv >= 30) {
curCount--;
cv = 0;
timertext.text = String(curCount);
if (curCount == 0) {
restart();
gotoAndStop("gameOverWon");
}
}
}
}
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = obstacles[i];
move(ob);
if (player.hitTestObject(obstacles[i])) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y - player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y - player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}
// applies basic velocity to enemies
function move(moveOb) {
moveOb.x -= moveOb.vx;
if (moveOb.x + moveOb.width/2 > right) {
moveOb.x = right - moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = -1;
}
if (moveOb.x - moveOb.width/2 < left) {
moveOb.x = left + moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = 1;
}
}
function bumpOb(p) {
if (p) {
p.removeEventListener(Event.ENTER_FRAME, updateOb);
if (p.parent) {
removeChild(p);
score--;
}
}
}
function restart() {
if(contains(player)) {
removeChild(player);
}
for (var i:int = 0; i < numOb; i++) {
if (contains(obstacles[i]) && obstacles[i] != null) {
removeChild(obstacles[i]);
obstacles[i] = null;
}
}
// returns a new array that consists of a range of elements from the original array,
// without modifying the original array
obstacles.slice(0);
}
function controls() {
if (rightKeyDown) {
velX += 3;
player.scaleX = 1;
}
if (leftKeyDown) {
velX -= 3;
player.scaleX = -1;
}
}
function isJumping() {
touchGround = false;
velY = -15;
}
//==================================================
// Sound control for background music
//==================================================
btnMute.addEventListener(MouseEvent.CLICK, mute);
function mute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(0);
btnMute.removeEventListener(MouseEvent.CLICK, mute);
btnMute.addEventListener(MouseEvent.CLICK, unmute);
}
function unmute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(1);
btnMute.removeEventListener(MouseEvent.CLICK, unmute);
btnMute.addEventListener(MouseEvent.CLICK, mute);
}

I had the same problem when I created interactive elements for animation. Check which layer the interactive object is on. A similar error occurred when the object overlapped something that was located on the layer above.

You can try...
1) Your Npc is a class/library object, right?
Give the source MC/Sprite, the instance name of moveOb or p.
2) or else try... Use function parameters (this is a better coding style):
(2a) Since you say..
var ob:Npc = obstacles[i];
move(ob);
ps: why not simplify (without var) as : move( obstacles[i] ); ...?
(2b) Your move function should specify a data type together with your parameter name...
//# applies basic velocity to enemies
//# Wrong...
//function move(moveOb) {
//# Better...
function move( moveOb : Npc ) {
//# Aso fix as...
function bumpOb(p : Npc ) {
By using function parameters, you can now give unique names to the (function's) input parameters but stay referencing the same (or compatible) data type.
Let me know how it goes.

The obstacles array may have null elements in the middle. What if you add a condition to continue if it's null?
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < obstacles.length; i++) {
var ob:Npc = obstacles[i];
if(!ob) continue;
move(ob);
if (player.hitTestObject(ob)) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y -
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y -
player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}

Related

In AS3 how would i add 2 buttons that would enable the player to move on press instead of using the arrow keys?

I got this code off the internet for the game Pong to work on my AS3 document for my assignment. However i'm pretty much a beginner at code and i'm trying to get this game to work on mobile as the assignment needs a game to work on it.
Because it uses arrow keys, i would like to basically just replace them with buttons instead, one for going up and one for going down. I just don't know the type of code that would allow me to do that.
Something like, when button is pressed, player moves up or down depending which button, but im not sure where to replace the code and what to get rid of.
Here's the "Pong" class file:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Pong extends MovieClip {
//constants
private var pongUp:MovieClip = new PongUp ;
private var pongDown:MovieClip = new PongDown ;
const ballspeed:int = 10;
const playerspeed:int = 7;
const computerspeed:int = 10;
const computerIntelligence:int = 7;//intelligence is 7 out of 10
//global variables
var vx:int = - ballspeed;// x component of velocity of ball (velocity is speed with direction)
var vy:int = ballspeed;// y component of velocity of ball
var v1:int = 0;// initial velocity of player
var v2:int = 0;// initial velocity of computer
var playerScore:int = 0;
var computerScore:int = 0;
var player:MovieClip = new PongPlayer ;
var computer:MovieClip = new PongComputer ;
var ball:MovieClip = new PongBall ;
public function Pong() {
//init();
addEventListener(Event.ADDED_TO_STAGE,init);
}
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
stage.addEventListener(Event.ENTER_FRAME,EnterFrame);
addChild(player);
addChild(computer);
addChild(ball);
player.x = 23;
player.y = 300;
computer.x = 637;
computer.y = 311;
ball.x = 308;
ball.y = 328;
addChild(pongUp);
pongUp.x = 25;
pongUp.y = 700;
addChild(pongDown);
pongDown.x = 530;
pongDown.y = 700;
}
// this function resets the game
function reset():void {
player.y = stage.stageHeight / 2;
computer.y = stage.stageHeight / 2;
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
if (Math.abs(Math.random() * 2) > 1)
{
vx = - ballspeed;
}
else
{
vx = ballspeed;
}
if (Math.abs(Math.random() * 2) > 1)
{
vy = - ballspeed;
}
else
{
vy = ballspeed;
}
}
//pongDown.addEventListener ( MouseEvent.MOUSE_DOWN,moveDown );
//function moveDown ( e:MouseEvent ): void
//{
//}
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
//This function is executed when a frame changes
function EnterFrame(event:Event):void {
//variable decleration
var pHalfHeight = player.height / 2;// half height of player(used for collisions)
var pHalfWidth = player.width / 2;// half width of player (used for collisions)
var bHalfHeight = ball.height / 2;// half height of ball(used for collisions)
var bHalfWidth = ball.width / 2;// half width of ball (used for collisions)
//moving the player
player.y += v1;
//limiting the motion of player (it should not move beyond the stageheight)
if (player.y + pHalfHeight > stage.stageHeight)
{
player.y = stage.stageHeight - pHalfHeight;
}
else if (player.y - pHalfHeight < 0)
{
player.y = 0 + pHalfHeight;
}
//moving the ball
ball.x += vx;
ball.y += vy;
//moving the computer automatically
if (Math.abs(Math.random() * 10) < computerIntelligence)
{
var d:int = computer.y - ball.y;
if (Math.abs(d) > pHalfHeight)
{
if ((d > 0))
{
v2 = - computerspeed;
}
else
{
v2 = computerspeed;
}
}
}
computer.y += v2;
//limiting the motion of computer (it should not move beyond the stageheight)
if (computer.y + pHalfHeight > stage.stageHeight)
{
computer.y = stage.stageHeight - pHalfHeight;
}
else if (computer.y - pHalfHeight < 0)
{
computer.y = 0 + pHalfHeight;
}
//collision with horizontal walls
if (ball.y + bHalfHeight >= stage.stageHeight || ball.y - bHalfHeight <= 0)
{
vy *= -1;
}
//collision with player and computer
if (ball.x - bHalfWidth <= player.x + pHalfWidth)
{
if (Math.abs(ball.y - player.y) <= pHalfHeight)
{
vx = ballspeed;
if ((v1 != 0))
{
vy = 2 * v1;
}
}
}
else if (ball.x + bHalfWidth >= computer.x - pHalfWidth)
{
if (Math.abs(ball.y - computer.y) <= pHalfHeight)
{
vx = - ballspeed;
if ((v2 != 0))
{
vy = v2;
}
}
}
//collision with vertical walls & updating scores
if (ball.x + bHalfWidth >= stage.stageWidth)
{
playerScore += 1;
reset();
}
else if (ball.x - bHalfWidth <= 0)
{
computerScore += 1;
reset();
}
//display the score on the textfield
//txtPlayer.text = String(playerScore);
//txtComputer.text = String(computerScore);
}
}
}
For mobile, you'll want to compile using AIR for Android or iOS. You can then replace:
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
with:
function KeyDown(event:TouchEvent):void {
if (event.stageY < player.y){
v1 = - playerspeed;
}else if (event.stageY > player.y){
v1 = playerspeed;
}
}
function KeyUp(event:TouchEvent):void {
v1 = 0;
}
Then replace:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
with:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(TouchEvent.TOUCH_BEGIN, KeyDown);
stage.addEventListener(TouchEvent.TOUCH_END, KeyUp);
And make sure to use TouchEvent instead of KeyboardEvent by replacing:
import flash.events.KeyboardEvent;
with:
import flash.events.TouchEvent;
Now when you hold your finger down on the screen, the "player" will move towards that Y location. If your game is using the X axis, just change the Ys to Xs!
Hope this helps!

Bullet fires perfectly in three directions, but not left

I'm quite new with actionscript, and have been scrapping together a little test game to sort of get used to the language, get my feet wet. The premise behind the game is pretty average, I have a character that can move in 8 directions, can pick up several keys that are randomly placed, and open a door when he possesses a key.
The problem comes in to play with the bullet shooting. I don't know much about trigonometry, so when a key is pressed, i just use the .rotate property to turn the player. I pass the .rotate integer into my bullet class and use that to tell which direction the bullet should travel. It works perfectly for the up, down, and right movements, but when the character is facing left the bullet is created but has no velocity whatsoever, and for the life of me I cannot figure out where the error in the code is.
If someone could look over my code and help me out, I would be much appreciated. I'm sure it's something simple that I'm just missing. I know it's a bit sloppy, so if there's any other tips you want to pass on to a novice please feel free!!
Thank you so much guys.
Main Class
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.text.TextField;
public class Main extends MovieClip
{
var player:Player;
var inventory:Inventory;
var invArray:Array = new Array();
var key:_Key;
var vx:int;
var maxSpeed:int;
var key_Up:Boolean;
var key_Down:Boolean;
var key_Left:Boolean;
var key_Right:Boolean;
var maxKey:int;
var keyCount:TextField;
var keysUp:int;
var door:Door;
var doorOpen:Boolean;
var wall1:Wall;
var wall2:Wall;
var wallCollide:Boolean;
var bulletTime:int;
var bulletLimit:int;
var bulletShoot:Boolean;
static var playerRotation:int;
public function Main()
{
init();
}
public function init():void
{
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
initPlayer();
initVariables();
initInventory();
initItems();
}
public function gameLoop(e:Event):void
{
movePlayer();
collisionDetection();
bullet();
}
public function keyDownHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = true;
break;
case 38 :
key_Up = true;
break;
case 39 :
key_Right = true;
break;
case 40 :
key_Down = true;
break;
case 32:
if(bulletShoot)
{
bulletShoot = false;
var newBullet:Bullet = new Bullet(player.rotation);
newBullet.x = player.x;
newBullet.y = player.y;
addChild(newBullet);
}
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = false;
break;
case 38 :
key_Up = false;
break;
case 39 :
key_Right = false;
break;
case 40 :
key_Down = false;
break;
}
}
public function movePlayer():void
{
if (key_Left && !key_Right)
{
player.x -= maxSpeed;
player.rotation = 270;
}
if (key_Right && !key_Left)
{
player.x += maxSpeed;
player.rotation = 90;
}
if (key_Up && !key_Down)
{
player.y -= maxSpeed;
player.rotation = 0;
}
if (key_Down && !key_Up)
{
player.y += maxSpeed;
player.rotation = 180;
}
/*if ( key_Left && key_Up && !key_Right && !key_Down )
{
player.rotation = 315;
}
if ( key_Right && key_Up && !key_Left && !key_Down )
{
player.rotation = 45;
}
if ( key_Left && key_Down && !key_Right && !key_Up )
{
player.rotation = 225;
}
if ( key_Right && key_Down && !key_Left && !key_Up )
{
player.rotation = 135;
}*/
}
public function initPlayer():void
{
player = new Player();
player.x = stage.stageWidth * .5;
player.y = stage.stageHeight * .5;
stage.addChild(player);
}
public function initVariables():void
{
vx = 0;
maxSpeed = 4;
key_Up = false;
key_Down = false;
key_Left = false;
key_Right = false;
maxKey = 3;
keysUp = 0;
doorOpen = false;
wallCollide = false;
bulletTime = 0;
bulletLimit = 12;
bulletShoot = true ;
}
public function collisionDetection():void
{
for (var i:int=0; i < invArray.length; i++)
{
key = invArray[i];
if (player.hitTestObject(key))
{
stage.removeChild(key);
invArray.splice(i, 1);
keysUp++;
//trace(keysUp);
i--;
keyCount.text = String(keysUp);
break;
}
}
if (player.hitTestPoint(door.x,door.y + 25,true) && (keysUp > 0) && ! doorOpen)
{
door.gotoAndStop(2);
keysUp--;
invArray.pop();
trace(keysUp);
keyCount.text = String(keysUp);
doorOpen = true;
}
if (player.hitTestObject(door) && (keysUp == 0) && ! doorOpen)
{
wallCollide = true;
}
if (player.hitTestObject(wall1))
{
wallCollide = true;
}
if (player.hitTestObject(wall2))
{
wallCollide = true;
}
if (wallCollide == true)
{
player.y += 4;
wallCollide = false;
}
}
public function initInventory():void
{
inventory = new Inventory();
inventory.x = stage.stageWidth * .15;
inventory.y = stage.stageHeight * .90;
stage.addChild(inventory);
keyCount = new TextField();
stage.addChild(keyCount);
keyCount.x = inventory.x - 8;
keyCount.y = inventory.y + 3;
keyCount.text = String(keysUp);
//keyCount.border = true;
keyCount.width = 20;
keyCount.height = 20;
}
public function initItems():void
{
while (invArray.length < maxKey)
{
key = new _Key ;
key.x = Math.random() * 550;
key.y = Math.random() * 300;
stage.addChild(key);
invArray.push(key);
}
door = new Door();
door.x = 250;
door.y = 25;
wall1 = new Wall();
stage.addChild(wall1);
wall1.x = door.x - 175;
wall1.y = door.y;
wall2 = new Wall();
stage.addChild(wall2);
wall2.x = door.x + 175;
wall2.y = door.y;
stage.addChild(door);
}
public function bullet():void
{
if (bulletTime < bulletLimit)
{
bulletTime++;
} else
{
bulletShoot = true;
bulletTime = 0;
}
}
}
}
Bullet Class
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip {
public var _root:Object;
public var speed:int = 10;
public var bulletRotation:int;
public function Bullet(pRotation:int) {
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, eFrame);
bulletRotation = pRotation;
}
private function beginClass(e:Event):void
{
_root = MovieClip(root);
}
private function eFrame(e:Event):void
{
if (bulletRotation == 0)
{
this.y -= speed;
}
else if (bulletRotation == 90)
{
this.x += speed;
}
else if(bulletRotation == 270)
{
this.x -= speed;
}
else if(bulletRotation == 180)
{
this.y += speed;
}
if(this.y < -1 * this.height)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
if(this.x < -1 * this.width)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
}
}
}
In Bullet class, change 270 to -90, at line 38:
else if(bulletRotation == -90)
{
this.x -= speed;
}

1046 AS3 Compile Time Error

I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
function moveBullets():void
{
for (var i:int = 0; i < bullets.length; i++)
{
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x <-bullets[i].width
|| bullets[i].x > stage.stageWidth + bullets[i].width
|| bullets[i].y < -bullets[i].width
|| bullets[i].y > stage.stageHeight + bullets[i].width)
{
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
function moveBaddies():void
{
for (var i:int = 0; i < baddies.length; i++)
{
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.

How Do I spawn Enemy at either the far left or the far right of the stage and have them move in to the center?

First I get This Error
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Game_fla::MainTimeline/testCollisions()[Game_fla.MainTimeline::frame1:205]
and here is my code
// ******* IMPORTS *****
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
//*****VARIABLES****
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var shootDown:Boolean = false;
var ySpeed:int = 0;
var xSpeed:int = 0;
var scrollX:int = 0;
var scrollY:int = 0;
var speedConstant:int = 5;
var friction:Number = 0.6;
var level:Number = 1;
var bullets:Array = new Array();
var container_mc:MovieClip;
var enemies:Array;
var tempEnemy:MovieClip;
// BUTTON EVENTS EITHER CLICKED OR NOT
left_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
right_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveRight);
up_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveUp);
shoot_btn.addEventListener(MouseEvent.MOUSE_DOWN, shootPressed);
left_btn.addEventListener(MouseEvent.MOUSE_UP, leftUp);
right_btn.addEventListener(MouseEvent.MOUSE_UP, rightUp);
up_btn.addEventListener(MouseEvent.MOUSE_UP, upUp);
stage.addEventListener(Event.ENTER_FRAME, makeEnemies);
player.gotoAndStop('still');
stage.addEventListener(Event.ENTER_FRAME,onenter);
function onenter(e:Event):void{
if (rightPressed == true && leftPressed == false){
player.x += 8;
player.scaleX = 1;
player.gotoAndStop("walking");
cloud.x -= 8;
} else if (leftPressed == true && rightPressed == false){
player.x -= 8;
player.scaleX = -1;
player.gotoAndStop('walking');
cloud.x += 8;
} else if(upPressed == true && leftPressed == false && rightPressed == false){
}
else{
rightPressed = false;
leftPressed = false;
player.gotoAndStop('still')}
}
// **** MOVEMENT CONTROLS *********
function shootPressed(e:MouseEvent):void{
shootDown = true;
if(shootDown == true){
fireBullet();
}
}
function fireBullet():void
{
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
var bullet:Bullet = new Bullet(player.x, player.y, playerDirection);
//bullets = new Array();
bullet.y = player.y + 8;
stage.addChild(bullet);
bullets.push(bullet);
trace(bullets);
}
// BUTTON FUNCTIONS
function moveLeft(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
leftPressed = true;
}else if (MouseEvent.MOUSE_UP) {
leftPressed = false;
}
}
function moveRight(e:MouseEvent):void
{
if (MouseEvent.MOUSE_DOWN){
rightPressed = true;
}else if (MouseEvent.MOUSE_UP){
rightPressed = false;
}
}
function moveUp(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
upPressed = true;
} else if (MouseEvent.MOUSE_UP) {
upPressed = false;
}
}
function leftUp(e:MouseEvent):void
{
leftPressed = false;
}
function rightUp(e:MouseEvent):void
{
rightPressed = false;
}
function upUp(e:MouseEvent):void
{
upPressed = false;
}
enemies = new Array();
//Call this function for how many enemies you want to make...
function makeEnemies(e:Event):void
{
var chance:Number = Math.floor(Math.random() * 60);
if (chance <= 2){
//Make sure a Library item linkage is set to Enemy...
tempEnemy = new enemy();
tempEnemy.speed = 80;
tempEnemy.x = Math.round(Math.random() * stage.stageWidth) * -10;
addChild(tempEnemy);
enemies.push(tempEnemy);
moveEnemies();
}
}
function moveEnemies():void
{
var tempEnemy:MovieClip;
for (var i:int =enemies.length-1; i>=0; i--)
{
tempEnemy = enemies[i];
tempEnemy.x += tempEnemy.speed;
tempEnemy.y = 285;
}
}
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
//Check for collisions between an enemies array and a Lasers array
function testCollisions(e:Event):void
{
var tempEnemy:MovieClip;
var tempLaser:MovieClip;
for (var i:int=enemies.length-1; i >= 0; i--)
{
tempEnemy = enemies[i];
for (var j:int=bullets.length-1; j>=0; j--)
{
tempLaser = bullets[j];
if (tempLaser.hitTestObject(tempEnemy))
{
removeChild(tempEnemy);
removeChild(tempLaser);
trace("BULLET HIT");
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
}
}
}
}
I Understand that I need to reference the parent whenever I removeChild in the testCollision function but I dont know where.
Also I want the zombies to spawn out of the stage and move in towards the center at a smooth speed with the code I have they just seem to spawn sort of rearly and always to the left of the stage. So I would need to spawn them off the stage and have them move in to the center and change their ScaleX position to change their dirention but I dont know how to do that Please help.
I think you can fix the error you listed by changing removeChild(tempLaser) to stage.removeChild(tempLaser) since the stage is where you added your bullets, so that's where you need to remove them from.
I'll give you a hint on the zombie movement, but you'll probably want to find a programming forum/friend/professor to help with general code design questions like this. In moveEnemies, you'll need to decide whether the zombie should move left/right (based on whether their x position is larger or smaller than the player's), and whether they should move up/down (based on whether their y position is larger or smaller than the player's).
For example, if their x position is larger than the player's, you would do tempEnemy.x -= tempEnemy.speed, and if smaller, you would do tempEnemy.x += tempEnemy.speed. But as I said, this site isn't really made for these types of design questions.

addEventListener() isn't detecting KEY_UP nor KEY_DOWN

My full code is
import flash.events.KeyboardEvent;
import flash.events.Event;
//init some variables
var speedX = 0;
var speedY = 0;
msg.visible = false;
var curLevel = 2;
var level = new Array();
var flagVar;
var won = false;
//Adding level platforms
for(var i = 0; i < numChildren; i++) {
if(getChildAt(i) is platform) {
level.push(getChildAt(i).getRect(this));
}
if(getChildAt(i) is flag) { flagVar = getChildAt(i).getRect(this); }
}
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
addEventListener(Event.ENTER_FRAME, loopAround);
function loopAround(e:Event) {
//horizontal movement
if(kLeft) {
speedX = -10;
} else if(kRight) {
speedX = 10;
} else {
speedX *= 0.5;
}
player.x += speedX;
//horizontal collision checks
for(var i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedX > 0) {
player.x = level[i].left - player.width;
}
if(speedX < 0) {
player.x = level[i].right;
}
speedX = 0;
}
}
//vertical movement
speedY += 1;
player.y += speedY;
var jumpable = false;
//Vertical collision
for(i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedY > 0) {
player.y = level[i].top - player.height;
speedY = 0;
jumpable = true;
}
if(speedY < 0) {
player.y = level[i].bottom;
speedY *= -0.5;
}
}
}
//JUMP!
if((kUp || kSpace) && jumpable) {
speedY=-20;
}
//Moving camera and other
this.x = -player.x + (stage.stageWidth/2);
this.y = -player.y + (stage.stageHeight/2);
msg.x = player.x - (msg.width/2);
msg.y = player.y - (msg.height/2);
//Checking win
if(player.getRect(this).intersects(flagVar)) {
msg.visible = true;
won = true;
}
//Check for next level request
if(kSpace && won) {
curLevel++;
gotoAndStop(curLevel);
won = false;
}
}
The section in question is
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
This was working fine last night, but today I moved it to a new keyframe and now it's not working. I'm not getting any errors (even if I debug). It just won't move the character or even show up in output.
I'm still quite new to as3, so I don't really know what to do.
Thanks in advance.
Edit: After playing with it a bit, I've found out that the reason it's not working is due to the menu. The menu has a single button and two text elements, which are fine. The code that I'm using on the menu is this:
import flash.events.MouseEvent;
stop();
var format:TextFormat = new TextFormat();
format.size = 26;
format.bold = true;
playGameButton.setStyle("textFormat", format);
stage.addEventListener(MouseEvent.CLICK, playGame);
function playGame(e:MouseEvent) {
if(e.target.name == "playGameButton") {
gotoAndStop(2);
}
}
If I use just gotoAndStop(2); it works fine, but with everything else it just goes to the second frame, and nothing else works after that.
Edit #2: I've narrowed it down even farther to the if statement itself.
if(e.target == playGameButton)
if(e.target.name == "playGameButton")
Both of those don't work. If I just remove the if statement all together it works perfectly fine.
there seems to be aproblem with this lines
if(getChildAt(i) is platform)
leads to error 1067: Implicit coercion of a value of type flash.display:MovieClip to an unrelated type Class
the rest of the code seems to be just fine
Try disabling your buttons mouseChildren.
playGameButton.mouseChildren = false;
Try e.currentTarget instead of e.target. From the documentation:
currentTarget : Object
[read-only] The object that is actively processing the Event object with an event listener.
target : Object
[read-only] The event target.
I'm not quite sure that this is your problem but the target vs currentTarget confusion has gotten me before.