1046 AS3 Compile Time Error - actionscript-3

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.

Related

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

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");
}
}

How to set only one object to spawn with a timer?

I am currently a beginner trying to learn programming with as3 so bear with me. I have this code so far and my game repeatedly spawns the Food2 (golden apple) but it does not stop. Here is my code so far:
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class Main extends MovieClip{
const speed:int = 10;
var score:int;
var vx:int;
var vy:int;
var gFood:Food;
var gFood2:Food2;
var head:SnakePart;
var SnakeDirection:String;
var snake:Array;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var myTimer:Timer = new Timer(10000,1);
public function Main(){
init();
gotoAndStop(1);
}
function init():void {
vx = 1; vy = 0;
score = 0;
snake = new Array();
SnakeDirection = "";
addFood();
myTimer.start();
head = new SnakePart();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
start1.addEventListener(MouseEvent.CLICK, startgame);
help1.addEventListener(MouseEvent.CLICK, helpplayer);
stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
}
private function startgame(event:MouseEvent):void {
gotoAndPlay(3);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
stop();
}
private function helpplayer(event:MouseEvent):void {
gotoAndPlay(2);
stop();
}
function addFood():void {
gFood = new Food();
gFood.x = 50 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
function addFood2():void {
gFood2 = new Food2();
gFood2.x = 70 + Math.random()*(stage.stageWidth-100);
gFood2.y = 70 + Math.random()*(stage.stageHeight-100);
addChild(gFood2);
}
function reset():void {
gotoAndStop(1);
score = 0;
removeChild(gFood);
removeChild(gFood2);
myTimer.stop();
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
SnakeDirection = "left";
}else if (event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "right";
}else if (event.keyCode == Keyboard.UP) {
SnakeDirection = "up";
}else if (event.keyCode == Keyboard.DOWN) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.LEFT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.UP ) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.DOWN){
SnakeDirection = "";
}
}
function onEnterFrame(event:Event):void {
Timerfood();
txtScore.text = "Score:" + String(score);
if(SnakeDirection == "left" && vx != 1) {
vx = -1;
vy = 0;
}
else if(SnakeDirection == "right" && vx != -1) {
vx = 1;
vy = 0;
}
else if(SnakeDirection == "up" && vy != 1) {
vx = 0;
vy = -1;
}
else if(SnakeDirection == "down" && vy != -1) {
vx = 0;
vy = 1;
}
if(head.x - head.width/2 <= 0){
score = 0;
reset();
}
if(head.x + head.width/2 >= stage.stageWidth){
score = 0;
reset();
}
if(head.y - head.height/2 <= 0){
score = 0;
reset();
}
if(head.y + head.height/2 >= stage.stageHeight){
score = 0;
reset();
}
for(var i = snake.length-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
head.x += vx*speed;
head.y += vy*speed;
for(var i = snake.length-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
if(head.hitTestObject(gFood)){
score += 1;
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
score += 2;
removeChild(gFood2);
bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
function Keyboard_a(event:KeyboardEvent):void {
if (event.keyCode == 82) {
resetgame();
}
}
function resetgame():void {
score = 0;
if (contains(head))
removeChild(head);
init();
}
}
function Timerfood():void {
var myTimer:Timer = new Timer(10000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void{
trace("Timer is Triggered");
addFood2();
}
myTimer.start();
}
}
}
It's hard to understand what specific logic you want to implement, but it looks like you need to create an enemy only once. And it looks like the problem is: you call the Timerfood method in the onEnterFrame listeners, which itself is called many times per second according to the framerate of your app (e.g. 30 times per second).
I would suggest you to remove the call of Timerfood from the onEnterFrame method, and put it in the end of the init method.
Well, my English is not very good, but I try tell the possible reason,
the method Timerfood() is called on method onEnterFrame(), that initialize myTimer for each frame, so may be the solution is, remove this line into TimerFood() method:
var myTimer:Timer = new Timer(10000,1);
and call TimerFood() only in startgame() method.
I hope you can understand me.

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;
}

TypeError: Error #1009: Cannot access a property or method of a null reference

I am creating a platformer game. However, I have encountered an error after creating a collision boundary on platform to make the player jump on the platform without dropping.
I have create a rectangle box and I export it as platForm
Here's the output of the error:
The error keep repeating itself over and over again....
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Boy/BoyMove()
Main class:
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class:
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 15;
//whether or not the main guy is jumping
//var mainJumping:Boolean = false;
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var gravity:Number = 10;
var theGround:ground = new ground();
//var theCharacter:MovieClip;
public var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, BoyMove);
}
public function BoyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (MovieClip(this).y > 500)
{
mainJumping = false;
MovieClip(this).y = 500;
}
this.y = currentY;
}
}
}
Platformer class: This is the class I want to set the boundary for the rectangle (platForm)
package
{
import flash.events.*;
import flash.display.MovieClip;
public class platForm extends MovieClip
{
var level:Array = new Array();
var classBoys:Boy = new Boy();
var speedx:int = MovieClip(classBoys).currentX;
public function platForm()
{
for (var i = 0; i < numChildren; i++)
{
if (getChildAt(i) is platForm)
{
level.push(getChildAt(i).getRect(this));
}
}
for (i = 0; i < level.length; i++)
{
if (MovieClip(classBoys).getRect(this).intersects(level[i]))
{
if (speedx > 0)
{
MovieClip(classBoys).x = level[i].left - MovieClip(classBoys).width/2;
}
if (speedx < 0)
{
MovieClip(classBoys).x = level[i].right - MovieClip(classBoys).width/2;
}
}
}
}
}
}
It's a little difficult to see exactly what is happening without being able to run your code, but the error is saying that something within your BoyMove() method is trying to reference a property (or method) of something that is null. Having looked at the BoyMove() method, I can see that there isn't a lot there that could cause this problem. The other two candidates would be
MovieClip(parent)
or
MovieClip(this)
You are attempting to access properties of both of those MovieClips. One of them must not be initialized as you expect. I suggest you do some basic debugging on that method by commenting out the lines with MovieClip(parent) and see if you still get the error. Then try the same with the line with MovieClip(this). That should be able enough to isolate the issue.

Making a simple chase AI in AS3

im attempting to make a simple game where zombies spawn out randomly from the edges of the screen and once they have spawned, they will get the last position of the player and keep moving towards that direction until they hit the stage and gets removed. However, i seem to be having a problem with the chase code. Even after reading tons of articles that offer the same chunk of code, im still unable to make it work (IM DOING IT WRONG ARRGH).
This is the main class
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
public class main extends MovieClip
{
private var left,right,up,down,fire,mouseRight,mouseLeft:Boolean;
private var speedX,speedY,mobPosX,mobPosY:int;
private var num:Number;
private var wizard:Player;
private var crosshair:Crosshair;
private var mobArray,magicArray:Array;
public function main()
{
//Hide mouse for crosshair
Mouse.hide();
crosshair = new Crosshair();
addChild(crosshair);
crosshair.x = stage.stageWidth;
crosshair.y = stage.stageHeight;
//Set initial speed
speedX = 0;
speedY = 0;
//Wizard stuff
fire = false;
wizard = new Player();
addChild(wizard);
wizard.x = stage.stageWidth / 2;
wizard.y = stage.stageHeight / 2;
//Mob stuff
mobArray = new Array();
magicArray = new Array();
//Initialize bool so movement doesn't get stuck on startup
up = false;
down = false;
left = false;
right = false;
}
public function startGame()
{
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.addEventListener(MouseEvent.CLICK, myClick);
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = true;
}
if (evt.keyCode == 38)
{
up = true;
}
if (evt.keyCode == 39)
{
right = true;
}
if (evt.keyCode == 40)
{
down = true;
}
if (evt.keyCode == 67)
{
trace(mobArray.length);
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = false;
speedX = 0;
}
if (evt.keyCode == 38)
{
up = false;
speedY = 0;
}
if (evt.keyCode == 39)
{
right = false;
speedX = 0;
}
if (evt.keyCode == 40)
{
down = false;
speedY = 0;
}
}
function myClick(eventObject:MouseEvent)
{
fire = true;
}
public function update(evt:Event)
{
//UI
crosshair.x = mouseX;
crosshair.y = mouseY;
//Start player
if (left && right == false)
{
speedX = -8;
}
if (up && down == false)
{
speedY = -8;
}
if (down && up == false)
{
speedY = 8;
}
if (right && left == false)
{
speedX = 8;
}
wizard.x += speedX;
wizard.y += speedY;
for (var i = mobArray.length - 1; i >= 0; i--)
{
//Start mob //if X is zero and Y > 10, spawn.
var m:Zombie = new Zombie();
m.chase((Math.atan2(mobArray[i].y - wizard.y,mobArray[i].x - wizard.x)/Math.PI * 180)); //applies trigo
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
m.x = mobPosX;
m.y = mobPosY;
mobArray.push(m);
addChild(m);
}
}
private function gameOver()
{
removeEventListener(Event.ENTER_FRAME,update);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
}
}//end class
}//end package
This is the zombie class
package
{
import flash.display.*;
import flash.events.*;
public class Zombie extends MovieClip
{
private var zombSpd:Number;
private var angle:Number;
public function Zombie()
{
zombSpd = 10;
}
public function chase(chaseAngle:Number)
{
angle = chaseAngle;
}
public function update()
{
this.x+=Math.cos(angle*Math.PI/180)*zombSpd;
this.y+=Math.sin(angle*Math.PI/180)*zombSpd;
}
}//end class
}//end package
Thank you :)
I just reread your code and see that you must read and learn more about programming before trying to create a game like this.
the reason your zombies are not spawning are because you never get inside the for loop. mob array length will be zero to start with, so the for loop will never happen.
take that for loop out and create a function to spawn enemies in your main class. you can use the code you use in your for loop as the code for this function example:
function spawn():void{
//code directly from your for loop, with a small change
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
var m:Zombie = new Zombie();
m.x = mobPosX;
m.y = mobPosY;
m.chase((Math.atan2(m.y - wizard.y,m.x - wizard.x)/Math.PI * 180)); //applies trigo
mobArray.push(m);
addChild(m);
}
now in your update function you must determine when you want enemies to spawn. you can do this by using a counter. Ill let you figure that part out, but if you want zombies to spawn continuously, (where your forloop in the update function was) add this:
//use a counter variable to determine when to execute spawn
spawn();
//loop through all zombies
for(var i:int = 0; i < mobArray.length; i++){
mobArray[i].update();
}
Steering behavior example at AdvanceEDActionScriptAnimation with abstracted interfaces and marshaling implementation.
Github:https://github.com/yangboz/as3SteeringBehavior