error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip - actionscript-3

Building a top down shooter, and after fixing some bugs an making everything work i am left with only one more.
error 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:MovieClip.
This is the Level.as where all the object are loaded
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.Timer;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.utils.*;
import flash.display.Shape;
import flash.display.DisplayObject
/**
*
*/
public class Level extends Sprite
{
//these booleans will check which keys are down
public var leftIsPressed:Boolean = false;
public var rightIsPressed:Boolean = false;
public var upIsPressed:Boolean = false;
public var downIsPressed:Boolean = false;
//how fast the character will be able to go
public var speed:Number = 5;
public var vx:Number = 0;
public var vy:Number = 0;
//how much time before allowed to shoot again
public var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 12;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 16;
//the spaceAuto's score
public var score:int = 0;
//this movieclip will hold all of the bullets
public var bulletContainer:MovieClip = new MovieClip();
//whether or not the game is over
public var gameOver:Boolean = false;
public var SpaceAuto:spaceAuto = new spaceAuto;
// publiek toegangkelijke verwijzing naar deze class
public static var instance:Level;
public var particleContainer:MovieClip = new MovieClip();
// constructor code
public function Level()
{
instance = this;
SpaceAuto.x = 135;
SpaceAuto.y = 350;
addChild(this.SpaceAuto);
addChild(this.bulletContainer);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
Project.instance.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
Project.instance.stage.addEventListener(Event.ENTER_FRAME, generateParticles);
//checking if there already is another particlecontainer there
if(!contains(particleContainer))
{
//this movieclip will hold all of the particles
addChild(this.particleContainer);
}
}
function keyDownHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = true; break;
case Keyboard.RIGHT : rightIsPressed = true; break;
case Keyboard.UP : upIsPressed = true; break;
case Keyboard.DOWN : downIsPressed = true; break;
}
if(e.keyCode == 32 && shootAllow)
{
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = SpaceAuto.x + SpaceAuto.width/2 - newBullet.width/2;
newBullet.y = SpaceAuto.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
}
}
function keyUpHandler(e:KeyboardEvent):void {
switch(e.keyCode) {
case Keyboard.LEFT : leftIsPressed = false; break;
case Keyboard.RIGHT : rightIsPressed = false; break;
case Keyboard.UP : upIsPressed = false; break;
case Keyboard.DOWN : downIsPressed = false; break;
}
}
function enterFrameHandler(e:Event):void {
vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed;
vy = -int(upIsPressed)*speed + int(downIsPressed)*speed;
SpaceAuto.x += vx;
SpaceAuto.y += vy;
if(cTime < cLimit)
{
cTime ++;
trace("++")
}
else
{
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 0;
}
//adding enemies to stage
if(enemyTime < enemyLimit)
{
//if time hasn't reached the limit, then just increment
enemyTime ++;
}
else
{
//defining a variable which will hold the new enemy
var newEnemy = new Enemy();
//making the enemy offstage when it is created
newEnemy.y = -1 * newEnemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newEnemy.x = int(Math.random()*(stage.stageWidth - newEnemy.width));
//then add the enemy to stage
addChild(newEnemy);
//and reset the enemyTime
enemyTime = 0;
}
//updating the score text
txtScore.text = 'Score: '+score;
if (gameOver == true)
{
loadScreenThree();
}
}
function generateParticles(event:Event):void
{
//so we don't do it every frame, we'll do it randomly
if(Math.random()*10 < 2){
//creating a new shape
var mcParticle:Shape = new Shape();
//making random dimensions (only ranges from 1-5 px)
var dimensions:int = int(Math.random()*5)+1;
//add color to the shape
mcParticle.graphics.beginFill(0x999999/*The color for shape*/,1/*The alpha for the shape*/);
//turning the shape into a square
mcParticle.graphics.drawRect(dimensions,dimensions,dimensions,dimensions);
//change the coordinates of the particle
mcParticle.x = int(Math.random()*stage.stageWidth);
mcParticle.y = -10;
//adding the particle to stage
particleContainer.addChild(mcParticle);
}
//making all of the particles move down stage
for(var i:int=particleContainer.numChildren - 1; i>=0; i--){
//getting a certain particle
var theParticle:DisplayObject = particleContainer.getChildAt(i);
//it'll go half the speed of the character
theParticle.y += speed*.5;
//checking if the particle is offstage
if(theParticle.y >= 400){
//remove it
particleContainer.removeChild(theParticle);
}
}
}
/**
* eventhandler voor als je op de tweede knop klikt
*/
private function loadScreenThree():void
{
// eerst opruimen!
cleanListeners();
// dan naar ander scherm
Project.instance.switchScreen( "derde" );
}
private function cleanListeners():void
{
stage.removeEventListener(Event.ENTER_FRAME, generateParticles);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}}
Where it goes wrong is in the Enemy Class in the eFrame Function. Here a loop runs trough the array bulletContainer from Level.as. A new variable is made and it should consist of the bullet that is in the loop out of the bulletContainer, and here comes the error in place
package{
//we have to import certain display objects and events
import Level;
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
//this just means that Enemy will act like a MovieClip
public class Enemy extends MovieClip
{
//VARIABLES
//this will act as the root of the document
//so we can easily reference it within the class
private var _root:Object;
//how quickly the enemy will move
private var speed:int = 5;
//this function will run every time the Bullet is added
//to the stage
public function Enemy()
{
//adding events to this class
//functions that will run only when the MC is added
addEventListener(Event.ADDED, beginClass);
//functions that will run on enter frame
addEventListener(Event.ENTER_FRAME, eFrame);
}
private function beginClass(event:Event):void
{
_root = Sprite(root);
}
private function eFrame(event:Event):void
{
//moving the bullet up screen
y += speed;
//making the bullet be removed if it goes off stage
if(this.y > 400)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
}
//checking if it is touching any bullets
//we will have to run a for loop because there will be multiple bullets
for(var i:int = 0;i<Level.instance.bulletContainer.numChildren;i++)
{
//numChildren is just the amount of movieclips within
//the bulletContainer.
trace("LOOOOOOOOOP");
trace(Level.instance.bulletContainer.getChildAt(i));
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget))
{
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
//also remove the bullet and its listeners
Level.instance.bulletContainer.removeChild(bulletTarget);
//bulletTarget.removeListeners();
//up the score
Level.instance.score += 5;
}
}
//hit testing with the user
if(hitTestObject(Level.instance.SpaceAuto))
{
//losing the game
trace("DOOOOOD");
removeListeners();
this.parent.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, eFrame);
Level.instance.gameOver = true;
}
}
public function removeListeners():void
{
this.removeEventListener(Event.ENTER_FRAME, eFrame);
}
}}
i have tried make it Sprite or anything else but i just dont know how to fix this so it wil take the bullet so i van see if it hits the Enemy
var bulletTarget:Sprite = Level.instance.bulletContainer.getChildAt(i);

getChildAt will return a DisplayObject type, and hitTestObject requires a parameter with DisplayObject type.
So try this in your Enemy's eFrame function.
var bulletTarget:DisplayObject = Level.instance.bulletContainer.getChildAt(i);

Related

how to reference a hit test object between .as files [AS3]

i'm trying to make a top down shooter game, and have been following tutorials here: http://gamedev.michaeljameswilliams.com/2008/09/17/avoider-game-tutorial-1/
and here: as3gametuts.com/2013/07/10/top-down-rpg-shooter-4-shooting/
i've managed to get shooting and movement, but i need to get a hit test object to register when the bullet (defined in its own seperate as class file) and the enemy (also defined in seperate file) come into contact. code below:
Enemy code:
package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
public function Enemy()
{
x = 100;
y = -15;
}
public function moveDownABit():void
{
y = y + 3;
}
}
}
Bullet code:
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
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 var enemy:Enemy;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180;
}
public function bullethit():void{
if (Bullet.hitTestObject(enemy)){
gameTimer.stop();
}
}
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);
}
}
}
}
Main.as document class code:
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Main extends MovieClip
{
public var player:Player;
public var bulletList:Array = []; //new array for the bullets
public var enemy:Enemy;
public var gameTimer:Timer;
public function Main():void
{
player = new Player(stage, 320, 240);
stage.addChild(player);
enemy = new Enemy();
addChild( enemy );
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
gameTimer.start();
stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true); //add an EventListener for the loop
}
public function moveEnemy( timerEvent:TimerEvent ):void
{
enemy.moveDownABit();
}
public function loop(e:Event):void //create the loop function
{
if(bulletList.length > 0) //if there are any bullets in the bullet list
{
for(var i:int = bulletList.length-1; i >= 0; i--) //for each one
{
bulletList[i].loop(); //call its loop() function
}
}
}
public function shootBullet(e:MouseEvent):void
{
var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true); //triggers the "bulletRemoved()" function whenever this bullet is removed from the stage
bulletList.push(bullet); //add this bullet to the bulletList array
stage.addChild(bullet);
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved); //remove the event listener so we don't get any errors
bulletList.splice(bulletList.indexOf(e.currentTarget),1); //remove this bullet from the bulletList array
}
}
}
As Vesper said, you'll want to do your checks in the Main class. You've already got a game loop set up, so you can just add the check in there:
public function loop(e:Event):void //create the loop function
{
if(bulletList.length > 0) //if there are any bullets in the bullet list
{
for(var i:int = bulletList.length-1; i >= 0; i--) //for each one
{
bulletList[i].loop(); //call its loop() function
// check to see if the enemy has been hit
if(enemy.hitTestObject(bulletList[i]))
{
// the enemy has been hit by the bullet at index i
}
}
}
}
Since you currently only have a single enemy, you're just testing each bullet against that one enemy. If you had more enemies, you'd want to keep an array of references to those enemies and do a nested loop, checking to see if any of the enemies were hit by any of the bullets.

Flash Error #1009

There's a problem with my AS3 code. The Error is:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mcEnemy/destroyEnemy()[/Users/deorka12/Documents/School/firstGame/mcEnemy.as:94]
at firstGame/checkEnemiesOffscreen()[/Users/deorka12/Documents/School/firstGame/firstGame.as:112]
at firstGame/gameLoop()[/Users/deorka12/Documents/School/firstGame/firstGame.as:63]
And this is how my code is:
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;
// public function kan je ook gebruiken in een ander as. file
// private function kan je alleen gebruiken in hetzelfde as. file
public class firstGame extends MovieClip
{
public var mcPlayer:MovieClip;
private var leftKeyIsDown:Boolean;
private var rightKeyIsDown: Boolean;
private var aMissileArray: Array;
private var aEnemyArray: Array;
public function firstGame (){
//initilaiz variables
aMissileArray = new Array ();
aEnemyArray = new Array ();
//trace("First Game Loaded");
//Listern for key presses and relesead
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//Setup game event loop
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// create a timer object
var tEnemyTimer : Timer = new Timer (1000);
// listener for timer intervals
tEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy);
// start out timer
tEnemyTimer.start();
}
private function addEnemy (e:TimerEvent) : void
{
//trace ("timer ticks")
// create a new enemy object
var newEnemy:mcEnemy = new mcEnemy ();
// add object to the stage
stage.addChild (newEnemy);
// add enemy to new enemy to a new enemy array
aEnemyArray.push(newEnemy);
trace (aEnemyArray.length);
}
private function gameLoop (e:Event) : void
{
playerControl();
clampPlayerToStage();
checkMissileOffscreen();
**checkEnemiesOffscreen();**
checkMissilesHitsEnemy();
}
private function checkMissilesHitsEnemy (): void
{
// loop trough current missiles
for (var i : int = 0 ; i < aMissileArray.length; i++)
{
// get our current missile in the i loop
var currentMissile : mcMissile = aMissileArray [i];
// loop trough all our enemies
// gebruik geen i want die is al gebruikt dus j
for (var j: int = 0 ; j < aEnemyArray.length; j++)
{
// get the current enemy in the j loop
var currentEnemy: mcEnemy = aEnemyArray [j];
// test if our current enemy is hitting our current missile
if(currentMissile.hitTestObject(currentEnemy))
{
// remove the missile
currentMissile.destroyMissile();
// remove the missile from missile array
aMissileArray.splice(i, 1);
// remove the enemy from the stage
**currentEnemy.destroyEnemy();**
// remove the enemy from the enemy array
aEnemyArray.splice(j, 1);
}
}
}
}
private function checkEnemiesOffscreen (): void
{
// loop trough all our enemies
for (var i:int = 0;i < aEnemyArray.length; i++)
{
// get our current ememy in the loop
var currentEnemy: mcEnemy = aEnemyArray [i];
// when enemy moves left and is has gone past the and of the left from the stage
if (currentEnemy.sDirection == "L" && currentEnemy.x - (currentEnemy.width/2))
{
// Remove enemy from our array
aEnemyArray.slice(i,1);
// Remove enemy from stage
currentEnemy.destroyEnemy();
} else
if (currentEnemy.sDirection == "R" && currentEnemy.x > stage.stageWidth + (currentEnemy.width/2))
{
// Remove enemy from our array
aEnemyArray.slice(i,1);
// Remove enemy from stage
currentEnemy.destroyEnemy();
}
}
}
private function checkMissileOffscreen():void
{
//Loop throw all our missiles in our missle array
// i = counter object
for (var i: int = 0; i < aMissileArray.length; i++)
{
//Get the current missile in the loop
var currentMissile : mcMissile = aMissileArray [i];
//Test if current missile is out the buttom of the screen
if (currentMissile.y > 450 )
{
//Remove current missile from the array
aMissileArray.splice(i,1);
//Destroy our missile
currentMissile.destroyMissile();
}
}
}
private function clampPlayerToStage ():void
{
// if our player is to the left of the stage
if (mcPlayer.x < (mcPlayer.width/2))
{
// set our player to left of the stage
mcPlayer.x = mcPlayer.width/2;
}
// if our player is to the right of the stage
else if (mcPlayer.x > (stage.stageWidth - (mcPlayer.width/2)))
{
//set our player to right of the stage
mcPlayer.x = stage.stageWidth - (mcPlayer.width/2);
}
}
private function playerControl ():void
{
// if our left key is down currently
if (leftKeyIsDown == true)
{
//move to left
mcPlayer.x -= 5;
}
// if our right key is currently down
if (rightKeyIsDown)
{
//move to right
mcPlayer.x += 5;
}
}
private function keyUp (e:KeyboardEvent): void
{
//trace(e.keyCode)
//if your left is released
if (e.keyCode == 37)
{
//left key is released
leftKeyIsDown = false;
}
//if your right is released
if (e.keyCode == 39)
{
//right key is released
rightKeyIsDown = false;
}
//if our spacebarr is released
if (e.keyCode == 32)
{
//fire a missile
fireMissile ();
}
}
private function fireMissile ():void
{
// create a new missisile object
var newMissile : mcMissile = new mcMissile ();
// add to stage
stage.addChild(newMissile);
// position missile
newMissile.x = mcPlayer.x;
newMissile.y = mcPlayer.y;
//add our new missile to our missile array
aMissileArray.push (newMissile);
trace(aMissileArray.length)
}
private function keyDown (e:KeyboardEvent): void
{
//trace(e.keyCode)
//if your left is pressed
if (e.keyCode == 37)
{
//left key is pressed
leftKeyIsDown = true;
}
//if your right is pressed
if (e.keyCode == 39)
{
//right key is pressed
rightKeyIsDown = true;
}
}
}
}
and my other code is:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class mcEnemy extends MovieClip {
public var sDirection:String;
private var nSpeed:Number;
public function mcEnemy()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd (e:Event): void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
init();
}
private function init ():void
{
// 3 frames
var nEnemies:Number = 3;
// pick random number between 1 and number of enemies
var nRandom:Number = randomNumber (1, nEnemies);
// Setup our playhead of this enemy clip to a random number
// Stop op frame 1,2 of 3
this.gotoAndStop(nRandom);
// Setup our enemys start position
setupStartPosition();
}
private function setupStartPosition (): void
{
// pick a random speed for the enemy
nSpeed = randomNumber (5,10);
// Pick random number for left or right, start position
var nLeftOrRight:Number = randomNumber (1,2);
// if our nLeftOrRight == 1 , enemy is on the left
if (nLeftOrRight == 1)
{
// start enemy on the left side
this.x = - (this.width/2);
sDirection = "R";
} else
{
// start enemy on the right side
this.x = stage.stageWidth + (this.width/2);
sDirection = "L";
}
// set a random hoogte for our enemy
// set a 2 varibele for min and max hoogte
var nMinAltitude: Number = stage.stageHeight/2;
var nMaxAltitude: Number = 400 - (this.height/2);
// Setup our enemies altitude to a random point between our min and max altitudes
this.y = randomNumber (nMinAltitude, nMaxAltitude);
// move our enemy
startMoving ();
}
private function startMoving (): void
{
addEventListener(Event.ENTER_FRAME, enemyLoop)
}
private function enemyLoop (e:Event ): void
{
// test in what direction our enemy is moving
// if our enemy is moving right
if (sDirection == "R")
{
// move our enemy right
this.x += nSpeed;
} else
{
this.x -= nSpeed;
}
}
// geeft random nummer tussen 0 en 1
function randomNumber (low:Number=0, high:Number=1) : Number
{
return Math.floor (Math.random() * (1+high-low)) + low;
}
public function destroyEnemy (): void
{
// remove enemys from the stage
**parent.removeChild(this);**
// remove any eventlisteners from enemy
removeEventListener(Event.ENTER_FRAME, enemyLoop);
}
}
}
I hope someone can help me. Sorry for my bad english.
The error indicates that the property parent is null, meaning that your mcEnemy object has no parent. The mcEnemy object has not been added to the display list.
To fix this you can check the parent property is set first:
if(parent)
{
parent.removeChild(this);
}

AS3 vertical shooter: Mouse click not working

I'm just trying to make a simple vertical shooter, one where the player's ship is controlled by the mouse and fires a laser when you click the mouse. However, when I try running the code, I keep getting the same error message:
"1046: Type was not found or was not a compile-time constant: MouseEvent."
The thing is, I declared the MouseEvent. I know I did. It is as follows:
--==--
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class SpaceShooter_II extends MovieClip //The public class extends the class to a movie clip.
{
public var army:Array; //the Enemies will be part of this array.
///*
//Laser Shots and Mouse clicks:
import flash.events.MouseEvent;
public var playerShot:Array; //the player's laser shots will fill this array.
public var mouseClick:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);
//*/
//Back to the rest of the code:
public var playerShip:PlayerShip; //This establishes a variable connected to the PlayerShip AS.
public var onScreen:GameScreen; //This establishes a variable that's connected to the GameScreen AS.
public var gameTimer:Timer; //This establishes a new variable known as gameTimer, connected to the timer utility.
///*
//Functions connected to Shooting via mouse-clicks:
public function mouseGoDown(event:MouseEvent):void
{
mouseClick = true;
}
public function mouseGoUp(event:MouseEvent):void
{
mouseClick = false;
}
//*/
//This function contains the bulk of the game's components.
public function SpaceShooter_II()
{
//This initiates the GameScreen.
onScreen = new GameScreen;
addChild ( onScreen );
//This sets up the enemy army.
army = new Array(); //sets the "army" as a NEW instance of array.
var newEnemy = new Enemy( 100, -15); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
army.push ( newEnemy ); //the new enemy is added to the army.
addChild( newEnemy ); //the new enemy is added to the game.
//This sets up the player's avatar, a spaceship.
playerShip = new PlayerShip(); //This invokes a new instance of the PlayerShip...
addChild( playerShip ); //...And this adds it to the game.
playerShip.x = mouseX; //These two variables place the "playerShip" on-screen...
playerShip.y = mouseY; //...at the position of the mouse.
///*
//This sets up the player's laser shots:
playerShot = new Array(); //sets the "army" as a NEW instance of array.
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
playerShot.push ( goodShot ); //the new enemy is added to the army.
addChild( goodShot ); //the new enemy is added to the game.
//*/
//This sets up the gameTimer, where a lot of the action takes place.
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
//This function contains the things that happen during the game (player movement, enemy swarms, etc.)
public function onTick( timerEvent:TimerEvent ):void
{
//This "if" statement is where the array that contains the enemy ships is initialized.
if ( Math.random() < 0.05 ) //This sets the number of ships showing up at once.
{
var randomX:Number = Math.random() * 800 //Generates a random number between 0 and 1.
var newEnemy:Enemy = new Enemy ( randomX, -15 ); //This shows where the enemy starts out--at a random position on the X plane, but at a certain points on the Y plane.
army.push( newEnemy ); //This adds the new enemy to the "army" Array.
addChild( newEnemy ); //This makes the new enemy part of the game.
}
//This "for" statement sends the enemies downward on the screen.
for each (var enemy:Enemy in army) //Every time an enemy is added to the "army" array, it's sent downward.
{
enemy.moveDown(); //This is the part that sends the enemy downward.
//And now for the collision part--the part that establishes what happens if the enemy hits the player's spaceship:
if ( playerShip.hitTestObject ( enemy ) ) //If the playerShip makes contact with the enemy...
{
gameTimer.stop(); //This stops the game.
dispatchEvent( new PlayerEvent(PlayerEvent.BOOM) ); //This triggers the game over screen in the PlayerEvent AS
}
}
//This, incidentally, is the player's movement controls:
playerShip.x = mouseX;
playerShip.y = mouseY;
///*
//And this SHOULD be the shooting controls, if the mouse function would WORK...
if ( mouseClick = true )
{
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new lasers. There's new variable in the statement, hence we call THIS a variable.
playerShot.push ( goodShot ); //the new laser is added to the army.
addChild( goodShot ); //the new laser is added to the game.
}
for each (var goodlaser: goodLaser in goodShot)
{
goodlaser.beamGood();
}
//*/
}
}
}
--==--
Sorry if the brackets are coming in uneven, I just wanted to outline the code in its entirety, and show the parts I added where things started going wrong, so someone can tell me what I need to do to make this work.
Basically, everything else works...but when I work on the things connected to the mouse clicking and the array with the lasers, the program stops working. The error seems to be connected to the functions "mouseGoUp" and "mouseGoDown," but I'm not sure how to fix that.
This assignment is due March 8. Can someone help me, please?
Add this import flash.events.MouseEvent; to the top of your class and it should work. You need to import everything you use. That's why you get that error.
As well as importing MouseEvent, in the initialisation of your game, you should add event listeners to the stage which listen for the MOUSE_DOWN and MOUSE_UP events:
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
What would be simpler, though, would be to do away with the 'mouseClick' variable and have just a single MouseEvent listener which listens for the MOUSE_DOWN event and trigger your missle launch from the handler.
I had a game like this if you want the entire source i can give it to you but the main parts are
var delayCounter:int = 0;
var mousePressed:Boolean = false;
var delayMax:int = 5;//How rapid the fire is
var playerSpeed:int = 5;
var bulletList:Array = [];
var bullet:Bullet;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler,false,0,true);
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler,false,0,true);
stage.addEventListener(Event.ENTER_FRAME,loop,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function loop(e:Event):void
{
player.rotation = Math.atan2(mouseY - player.y,mouseX - player.x) * 180 / Math.PI + 90;
if (bulletList.length > 0)
{
for each (bullet in bulletList)
{
bullet.bulletLoop();
}
}
if (mousePressed)
{
delayCounter++;
if ((delayCounter == delayMax))
{
shootBullet();
delayCounter = 0;
}
}
if (upPressed)
{
player.y -= playerSpeed;
}
if (downPressed)
{
player.y += playerSpeed;
}
if (leftPressed)
{
player.x -= playerSpeed;
}
if (rightPressed)
{
player.x += playerSpeed;
}
}
function mouseDownHandler(e:MouseEvent):void
{
mousePressed = true;
}
function mouseUpHandler(e:MouseEvent):void
{
mousePressed = false;
}
function shootBullet():void
{
var bullet:Bullet = new Bullet(stage,player.x,player.y,player.rotation - 90);
bulletList.push(bullet);
stage.addChildAt(bullet,1);
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = true;
}
if (event.keyCode == 83)
{
downPressed = true;
}
if (event.keyCode == 65)
{
leftPressed = true;
}
if (event.keyCode == 68)
{
rightPressed = true;
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = false;
}
if (event.keyCode == 83)
{
downPressed = false;
}
if (event.keyCode == 65)
{
leftPressed = false;
}
if (event.keyCode == 68)
{
rightPressed = false;
}
}
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;//speed that the bullet will travel at
private var xVel:Number = 5;
private var yVel:Number = 5;
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;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180;
}
public function bulletLoop():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)
{
deleteBullet();
}
}
public function deleteBullet()
{
this.visible=false
this.x=9999
this.y=9999
}
}
}

Falling object and repeating in a loop ( Action Script 3.0)

I am trying to make a symbol (made a special class for it) to fall continuously until a timer reaches 0. Also I would like this rock to repeat and show in random places on the stage. I can't figure out how to code that. Pretty much I am still a newbie to action script 3.0.
This is what I have so far:
The Main
package {
import flash.display.Sprite;
import Game_Objects.TinyBird;
import Game_Objects.Rock;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends Sprite {
private var userbird:TinyBird;
private var obstacle:Rock;
//containers.
private var obstacleContainer:Sprite = new Sprite();
//timers.
private var enemySpawn:Timer;
public function Main() {
// The main code of the game
// The Bird has to avoid rocks by moving left and right
// Obstacles = rocks
// The Birdie will be controlled by the keyboard
// As long as Birdie alive=1 the loop will continue until alive=0 (where 1=true and 0=false) or timer reaches 0
// if the bird will hit an object it will die (collision detection)
this.userbird = new TinyBird(stage.stageWidth/2, stage.stageHeight-20);
this.obstacle = new Rock;
obstacleContainer.addChild(obstacle);
addChild(userbird);
stage.addEventListener(Event.ENTER_FRAME, startpulse)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keymove);
// event to count the passed rocks in order to set score.
stage.addEventListener(obstacle.KILLED, deadEnemy);
}
private function startpulse(evt:Event):void {
// makes the bird pulsate
this.userbird.pulse_animation();
}
private function keymove(evt:KeyboardEvent):void {
// the keyboard movements for the bird
// if leftArrow = pressed -> tiny bird will move left. Else if rightArrow = pressed -> tiny bird will move right
if (evt.keyCode == Keyboard.LEFT) {
this.userbird.left();
} else if (evt.keyCode == Keyboard.RIGHT) {
this.userbird.right();
}
}
// The obstacle objects are going to fall randomly
private function spawn(e:TimerEvent):void {
// calculate a random starting position
var xPos:Number = Math.floor(Math.random()*stage.stageWidth);
// calculate a random speed between 2 and 6
var speed:Number = Math.floor(Math.random()*4+2) ;
// create the new rock
var enemy:Rock = new Rock(xPos, 42, speed, stage.stageWidth, stage.stageHeight);
// add it to the container
this.obstacleContainer.addChild(enemy);
enemy.name = "Rock " + Rock.createdCount;
}
private function deadEnemy(e:Event) {
var obj:Rock = (e.object as Rock);
this.objectContainer.removeChild(obj)
}
}
}
And this is the rock symbol:
package Game_Objects {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.Timer ;
import flash.events.TimerEvent ;
public class Rock extends Sprite {
// The Rock is the obstacle that, if colided with the bird, the game is over.
// public function properties
static public var _createdCount:int = 0;
// private function properties
private var speed:Number;
private var _score:Number = 4;
private var scoreCounter:Number = 0;
// Classes methods
public static function get createdCount():int {
return _createdCount;
}
// instance methods
// Initialization
public function Rock(x:Number, y:Number, s:Number, maxX:Number = 0, maxY:Number = 0) {
// set the speed
this.speed = s;
// If the rock goes off the stage, then
if (x < this.width/2) {
// Put on at left
this.x = this.width/2;
// else if x would put the rocks beyond right side of the stage then
} else if (x > maxX - this.width/2) {
// Position the rock on the stage.
this.x = maxX-this.width/2;
} else {
// Otherwise position at x
this.x = x;
}
// same for Y
if (y < this.height/2) {
this.y = this.height/2;
} else if (y > maxY - this.height/2) {
this.y = maxY-this.height/2;
} else {
this.y = y;
}
// Creating the animation loop in order to repeat the falling motion of the rocks.
configUI();
this.addEventListener(Event.ENTER_FRAME, drop);
// adding a boolean type of loop, taken from
// http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001283.html#374074
this.cacheAsBitmap = true;
// Add 1 to the public var in order to keep track of the rocks
_createdCount++;
}
// protected function
protected function configUI():void {
}
// private function
private function drop(e:Event) {
// in order to show the dropping effect
// The falling of the rocks
this.y += this.speed;
// if at bottom of stage then
if (this.y-this.height >= stage.stageHeight) {
// Set score to +1 as reward for not hitting the rock.
this._score++;
// Kill the rock that has reached the bottom of the stage
}
}
}
}

Error: #1009: Type Error (Line #114)

I'm sort of a noob to flash, but I am programming a game right now, and I am trying to make my character move but i am getting error #1009 Here is my code in my "GameState".
Basically it errors out on any Keypress, I have my character named player (Player in the library) and it has another movie clip within it named WalkDown (I gave it an instance name of walkDown on the timeline) I am not really sure whats going on. Specifically it errors out on the line where its calling the frame name. Any help would be appreciated!
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class GameState extends MovieClip {
private var player:MovieClip;
private var walking:Boolean = false;
// is the character shooting
//private var shooting:Boolean = false;
// wlaking speed
private var walkingSpeed:Number = 5;
private var xVal:Number = 0;
private var yVal:Number = 0;
public function GameState() {
// constructor code
player = new Player();
addChild(player);
player.x = 300;
player.y = 300;
player.gotoAndStop("stance");
this.addEventListener(Event.ADDED_TO_STAGE, initialise);
}
private function initialise(e:Event){
// add a mouse down listener to the stage
//addEventListener(MouseEvent.MOUSE_DOWN, startFire);
// add a mouse up listener to the stage
//addEventListener(MouseEvent.MOUSE_UP, stopFire);
player.addEventListener(Event.ENTER_FRAME,motion);
stage.addEventListener(KeyboardEvent.KEY_UP,onKey);
// add a keyboard down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, offKey);
stage.focus = stage;
// Add keyboard events
}
private function motion(e:Event):void{
// if we are currently holding the mouse down
//if (shooting){
//FIRE
//fire();
//}
player.x += xVal;
player.y += yVal;
}
//private function startFire(m:MouseEvent){
//shooting = true;
//}
//private function stopFire(m:MouseEvent){
//shooting = false;
//}
private function onKey(evt:KeyboardEvent):void
{
trace("key code: "+evt.keyCode);
switch (evt.keyCode)
{
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.S :
yVal = - walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.A :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.D :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
}
}
private function offKey(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.W :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.S :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.A :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.D :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
}
}
// Players Motion
private function fire():void{
var b= new Bullet();
// set the position and rotation of the bullet
b.rotation = rotation;
b.x = x;
b.y = y;
// add bullets to list of bullets
MovieClip(player).bullets.push(b);
// add bullet to parent object
player.addChild(b);
// play firing animation
player.shooting.gotoAndPlay("fire");
}
}
}
You were saying the Error #1009 ( Cannot access a property or method of a null object reference ) arises when you do
player.walkDown.gotoAndPlay("walking");
If so, that is because you have to first go to the frame where the WalkDown MovieClip is in before you can access it.
If say your "stance" frame is in frame 1 and your WalkDown MovieClip is in frame 2. Your code in the onKey function should look like:
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.gotoAndStop(2); // player.walkDown is now accessible //
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;