I have a vertical shooter game I'm working on. I need to find a way to make random objects(enemies) drop down from the top. At the moment I've got 1 enemy that drops down randomly from the top which is working. here is the code I'm using.
Main code
// Full Screen Command
fscommand("fullscreen","true");
stop();
//center player on screen
mcMain.x = 880,45;
mcMain.y = 940,40;
//these booleans will check which keys are down
var leftDown:Boolean = false;
var upDown:Boolean = false;
var rightDown:Boolean = false;
var downDown:Boolean = false;
//how fast the character will be able to go
var mainSpeed:int = 25;
//how much time before allowed to shoot again
var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
var cLimit:int = 12;
//whether or not the user is allowed to shoot
var shootAllow:Boolean = true;
//how much time before another enemy is made
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
var enemyLimit:int = 16;
//the player's score
var score:int = 0;
//this movieclip will hold all of the bullets
var bulletContainer:MovieClip = new MovieClip();
addChild(bulletContainer);
//whether or not the game is over
var gameOver:Boolean = false;
//adding a listener to mcMain that will move the character
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
//checking if the key booleans are true then moving
//the character based on the keys
if(leftDown){
mcMain.x -= mainSpeed;
}
if(upDown){
mcMain.y -= mainSpeed;
}
if(rightDown){
mcMain.x += mainSpeed;
}
if(downDown){
mcMain.y += mainSpeed;
}
//keeping the main character within bounds
if(mcMain.x <= 0){
mcMain.x += mainSpeed;
}
if(mcMain.y <= 0){
mcMain.y += mainSpeed;
}
if(mcMain.x >= stage.stageWidth - mcMain.width){
mcMain.x -= mainSpeed;
}
if(mcMain.y >= stage.stageHeight - mcMain.height){
mcMain.y -= mainSpeed;
}
//Incrementing the cTime
//checking if cTime has reached the limit yet
if(cTime < cLimit){
cTime ++;
} 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;
}
//this listener will listen for down keystrokes
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void{
//making the booleans true based on the keycode
//WASD Keys or arrow keys
if(event.keyCode == 37 || event.keyCode == 65){
leftDown = true;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightDown = true;
}
//checking if the space bar is pressed and shooting is allowed
if(event.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 = mcMain.x + mcMain.width/2 - newBullet.width/2;
newBullet.y = mcMain.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
mcMain.gotoAndPlay(1);
}
}
//this listener will listen for keys being released
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void{
//making the booleans false based on the keycode
if(event.keyCode == 37 || event.keyCode == 65){
leftDown = false;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightDown = false;
}
}
enemy class
package{
//we have to import certain display objects and events
import flash.display.MovieClip;
import flash.events.*;
//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 = MovieClip(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 > stage.stageHeight){
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.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<_root.bulletContainer.numChildren;i++){
//numChildren is just the amount of movieclips within
//the bulletContainer.
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:MovieClip = _root.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);
_root.removeChild(this);
//also remove the bullet and its listeners
_root.bulletContainer.removeChild(bulletTarget);
bulletTarget.removeListeners();
//up the score
_root.score += 5;
}
}
//hit testing with the user
if(hitTestObject(_root.deadLine)){
//losing the game
_root.gameOver = true;
_root.gotoAndStop('lose');
}
//checking if game is over
if(_root.gameOver){
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
}
}
}
}
I'm using the tutorial from here : http://www.flashgametuts.com/tutorials/as3/how-to-make-a-vertical-shooter-in-as3-part-1/
any help is much appriciated.
I used to make games in flash and I used this condition to constantly add Enemies in my game.
if (Math.floor(Math.random() * 90) == 5){
under this condition you can use your code do add 1 enemy randomly
I think you shold get a timer class conected to your main code.
get a global counter.
int count=0;
int timeElapsedToNewEnemy = int((Math.random()*10+1)*10);
//get u a number from 10 to 100
get ur timer
var time:Timer=new Timer(100,0);// each 1/10 seconds
time.start();
time.addEventListener(TimerEvent.TIMER, countTime);
get ur function for timer
function countTime(e:TimerEvent):void
{//increment ur timer
count++;
if (cont == timeElapsedToNewEnemy)
{
cont=0;//restar ur counter..
//createUrNewEnemyHere
//get a new timeElapsedToEnemy
timeElapsedToNewEnemy = int((Math.random()*10+1)*10);
}
}
now u can easily adjust it to create random enemys each random x time.
let me know if its work for u
Thanks guys, but i found a solution.
var newEnemy = new (getDefinitionByName("Enemy"+Math.floor(Math.random()*4)));
and then created different movieclips of the enemy as enemy
Related
I have been making this game in AS3 and the basics work. The thing i am having trouble with is making a 'start' menu appear when the game starts but also when the player dies. I have been trying the .visible code but that didn't seem to work.
Question: What code do i add to my game that makes the start button appear when the game starts but also when the player dies. Code:
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
public class Main extends MovieClip{
//constants
const gravity:Number = 1.5; //gravity of the game
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the bird to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Thanks in advance!
Draw a Box (with colour fill but no outline). Convert to MovieClip type. Give a name eg: "Menu"
It will be
a container for your menu. Add content by double-clicking it, to add
graphics & text on new layers. Or if you have already have content on some other frames, then just "cut frames" and later do a "paste frames" inside the timeline of this new movieClip.
When you converted, it was added to the Library section
(ctrl + L). Find it ("Menu") in the library and right-click then choose "properties". In
linkage section click "export for actionscript". The Class name should become "Menu" automatically. Now just click "OK".
Example usage in game code.. (ie: To add to screen or remove etc)
//# load the movieClip...
var Menu_Screen : Menu = new Menu(); //# Menu is linkage name given in Library
//# Adding to screen...
gameContainer_MC.addChild( Menu_Screen );
gameCcontainer_MC.removeChild( Menu_Screen );
//# Controlling the movieClip...
Menu_Screen.x = 50;
gameContainer_MC.Menu_Screen.x = 50;
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
}
}
}
My game starts with a start frame. click a button to the game. if I hit an object I go to game over screen. Everytime I hit the start over button on the game over screen my characters controls get faster. I have set no variables for speed, simply just "mc_guy.x +=3" or .y , etc. If I had to say by how much faster I would want to say that the speed doubles.
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
//prevent game loop
stop();
// event listeners for movement
mc_Guy.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownGuy);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpGuy);
// this array holds references to all the keys
var keys:Array = [];
//initiate default values
fuelGauge.height = 100;
//Gravity
addEventListener(Event.ENTER_FRAME,Gravity)
var GyAmt:Number = 5;
function Gravity(e:Event){
mc_Guy.y += GyAmt;
if (gameFloor.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor.y;}
else if (gameFloor2.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor2.y;}
else if (gameFloor3.hitTestObject(mc_Guy)){
mc_Guy.y = gameFloor3.y;}}
// the event listeners
function update(e:Event):void
{
if (keys[Keyboard.RIGHT])
{
mc_Guy.x += 3;
}
if (keys[Keyboard.LEFT])
{
mc_Guy.x -= 3;
}
if (keys[Keyboard.SPACE]){
mc_Guy.y -= 10;
//drain fuel
fuelGauge.height -= 1;
gaugePercent.text = String(fuelGauge.height)
if (fuelGauge.height == 0){
nextFrame();}}
}
function onKeyDownGuy(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
function onKeyUpGuy(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
//Array storing each wall
var MC_wall:Array = new Array(mc_Wall,mc_Wall2,mc_Wall5,
mc_Wall6,mc_Wall7,mc_Wall8,mc_Wall9,mc_Wall10,mc_Wall11,mc_Wall12, mc_Wall13)
//Collision Detection
addEventListener(Event.ENTER_FRAME,loop);
function loop(e:Event){
var i:Number = 0;
do {
if (MC_wall[i].hitTestObject(mc_Guy)){
nextFrame();}
i++;
} while (i < MC_wall.length);
/* for (var i:Number = 0; i < MC_wall.length; i++){
if (MC_wall[i].hitTestObject(mc_Guy)){
nextFrame();}
}*/
if(mc_Guy.hitTestPoint(mc_WallRun.x, mc_WallRun.y, false)){
nextFrame();}
else if(mc_Guy.hitTestObject(fuelPowerup)){
removeChild(fuelPowerup);
fuelGauge.height = 100;
gaugePercent.text = String(fuelGauge.height)}
else if(mc_Guy.hitTestObject(doorKey)){
removeChild(doorKey)
//open door
mc_Wall13.height -=20
mc_Wall13.y -= 10
}
}
//Object Movement
addEventListener(Event.ENTER_FRAME, onEnterFrame);
var spinSpeed:Number=6;
var axisMove:Number = 90;
var axisMovement:Number = 3;
function onEnterFrame(event:Event):void
{
mc_WallRun.rotation+=spinSpeed;
//count the movement on axis and move
axisMove -= 3;
mc_Wall9.x += axisMovement;
gameFloor3.x += axisMovement * .9;
if(axisMove <= 0){
axisMove += 90
axisMovement = axisMovement*-1
}
}
Gameover frame:
import flash.events.MouseEvent;
stop();
restartGame.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
function playAgain(event:MouseEvent):void{
prevFrame();
}
It sounds like when you restart your game
mc_Guy.addEventListener(Event.ENTER_FRAME, update);
is called again, without removing the previously added listener.
So update is now called two times on Event.ENTER_FRAME, and then once more per frame per game reset, causing the guy to move faster.
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;
/Question/
I have been at this for about a week and still can't find the problem.
I used trace statements but I cant tell whether is this or that. As I am still quite still inexperienced myself. I am using Flash Develop. thanks.
/* This is the error I am getting
I am trying remove the dango once it gets destroyed and remove it again after the game ends */
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mcDango/destoryDango()[J:\catchMeDango\mcDango.as:72]
at catchMeDango/checkEndGameCondition()[J:\catchMeDango.as:195]
at catchMeDango/gameLoop()[J:\catchMeDango\catchMeDango.as:171]
---------------------------------------------------------------------------------------
/*This is for catchMeDango doc */
package
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.utils.Timer;
/**
* ...
* #author
*/
public class catchMeDango extends MovieClip
{
public var skewerPlayer:MovieClip;
private var leftKeyIsDown:Boolean;
private var rightKeyIsDown:Boolean;
private var upKeyIsDown:Boolean;
private var downKeyIsDown:Boolean;
private var aDangoArray:Array;
private var aBlackDangoArray:Array;
public var scoreTxt:TextField;
public var lifeTxt:TextField;
public var menuEnd:mcEndGameScreen;
private var nScore:Number;
private var nLife:Number;
private var tDangoTimer:Timer;
private var tBlackDangoTimer:Timer;
private var menuStart:mcStartGameScreen;
private var startHow:Loader;
public function catchMeDango()
{
//hides the endGameScreen
menuEnd.hideScreen();
//Create loader object
var startLoader:Loader = new Loader();
//Add event listener to listen the complete event
startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
//Load our loader object
startLoader.load(new URLRequest("startGameScreen.swf"));
}
private function startHowToPlay(e:Event):void
{
//Create loader object
startHow = new Loader();
//Add event listener to listen the complete event
startHow.contentLoaderInfo.addEventListener(Event.COMPLETE, HowToPlay);
//Load our loader object
startHow.load(new URLRequest("howToPlay.swf"));
}
private function HowToPlay(e:Event):void
{
//add the how to play movie clip to stage
addChild(startHow);
startHow.addEventListener("BEGIN_GAME", playGameAgain);
}
private function startLoaded(e:Event):void
{
//Get a reference to the loaded movieclip
menuStart = e.target.content as mcStartGameScreen;
//Listen for start game event
menuStart.addEventListener("START_GAME", playGameAgain);
menuStart.addEventListener("HOW_TO_PLAY", startHowToPlay);
//Add to stage
addChild(menuStart);
}
private function playGameAgain(e:Event):void
{
//I had to remove this function becuase is was causing errors
//When I click on the "how to play" then go back to the start screen, it hides fine with no issues
//startHow.visible = false;
menuStart.visible = false;
//set keyboard control to false
leftKeyIsDown = false;
rightKeyIsDown = false;
upKeyIsDown = false;
downKeyIsDown = false;
//Initialize variables
aDangoArray = new Array();
aBlackDangoArray = new Array();
nScore = 0;
nLife = 1;
skewerPlayer.visible = true;
menuStart.hideScreen();
menuEnd.addEventListener("PLAY_AGAIN", playGameAgain);
menuEnd.hideScreen();
updateScoreText();
updateLifeText();
//trace ('Catch Me Dango Loaded');
//Set up listerners for when an key is pressed
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
//Set up a game loop listener
stage.addEventListener(Event.ENTER_FRAME, gameLoop)
//Create a timer object for Dango for every 1 second
tDangoTimer = new Timer(1000)
//Listen for timer ticks/intervals
tDangoTimer.addEventListener(TimerEvent.TIMER, addDango)
//Start timer object
tDangoTimer.start();
//Create a timer object for Black Dango for every 10 seconds
tBlackDangoTimer = new Timer(10000)
//Listen for timer ticks/intervals
tBlackDangoTimer.addEventListener(TimerEvent.TIMER, addBlackDango)
//start timer object
tBlackDangoTimer.start();
}
//Display Score Text (Starting form: 0)
private function updateScoreText():void
{
scoreTxt.text = "Score: " + nScore;
}
//Display Life Text (Starting from: 5)
private function updateLifeText():void
{
lifeTxt.text = "Life: " + nLife;
}
private function addBlackDango(e:TimerEvent):void
{
//create new black dango object
var newBlackDango:mcBlackDango = new mcBlackDango();
//Add our new black dango
stage.addChild(newBlackDango);
aBlackDangoArray.push(newBlackDango);
trace(aBlackDangoArray.length);
}
private function addDango(e:TimerEvent):void
{
//create new dango(enemy) object
var newDango:mcDango = new mcDango();
//Create enemy to the stage
stage.addChild(newDango);
//Add our new dango(enemy) to dango(enemy) array collection
aDangoArray.push(newDango);
trace(aDangoArray.length);
}
private function gameLoop(e:Event):void
{
playerContorl();
clampPlayerToStage();
checkDangosOffScreen();
checkSkewerHitsDango();
checkBlackDangosOffScreen();
checkSkwerHitsBlackDango();
checkEndGameCondition();
}
//HELP
private function checkEndGameCondition():void
{
//Check if the player has 0 life left
if (nLife == 0)
{
//Stop player movement
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//Hide the player
skewerPlayer.visible = false;
//Stop spawning dango and black dango
tDangoTimer.stop();
tBlackDangoTimer.stop();
//Clear the dango currently on screen
for each(var dango:mcDango in aDangoArray)
{
//this destory function had to be removed as well. because it was destorying the dango twice when it was already removed from the stage.
//by commenting out this, it was able to destory and remove without any errors and only doing it once.
//Destory the dango the were curretly up to in the for loop
dango.destoryDango();
trace("black dango removed")
//Remove from dango from dango array
aDangoArray.splice(0, 1);
}
//Clear the black dango currently on screen
for each(var blackDango:mcBlackDango in aBlackDangoArray)
{
//Destory the dango tat were curretly up to in the for loop
blackDango.destoryBlackDango();
//Remove from dango from dango array
aBlackDangoArray.splice(0, 1);
}
//Stop the game loop
if (aDangoArray.length == 0 && aBlackDangoArray.length == 0)
{
stage.removeEventListener(Event.ENTER_FRAME, gameLoop);
}
//Show end game screen
menuEnd.showScreen();
}
}
// Checks if the Skewer Hits or makes conatct with the Black Dango
private function checkSkwerHitsBlackDango():void
{
//Loop through our current Black dango
for (var i:int = 0; i < aBlackDangoArray.length; i++)
{
//Get our current Black Dango in the loop
var currentBlackDango:mcBlackDango = aBlackDangoArray[i];
//Test if our skewer is hitting the black dango
if (skewerPlayer.hitTestObject(currentBlackDango))
{
//remove the current dango from stage
currentBlackDango.destoryBlackDango()
//Remove the dango from out dango array
aBlackDangoArray.splice(i, 1);
//Minus one to our score
nScore--;
updateScoreText();
//Minus one to our life
nLife--;
updateLifeText();
}
}
}
// Remove the black dango of the stage and from the array
private function checkBlackDangosOffScreen():void
{
//loop through all our black dango
for (var i:int = 0; i < aBlackDangoArray.length; i++)
{
//Get our current dango in the loop
var currentBlackDango:mcBlackDango = aBlackDangoArray[i];
//When dango starts on the top AND our curent enemy has gone past the bottom side if the stage
if (currentBlackDango.y > (stage.stageHeight + currentBlackDango.y / 2))
{
//Remove black dango (enemy) from array
aBlackDangoArray.splice(i, 1);
//Remove black dango (enemy) from stage
currentBlackDango.destoryBlackDango();
}
}
}
// Checks if the Skewer Hits or makes conatct with the Dango
private function checkSkewerHitsDango():void
{
//Loop through all our current dango
for (var i:int = 0; i < aDangoArray.length; i++)
{
//Get our current dango in the loop
var currentDango:mcDango = aDangoArray[i];
//Test if our skewer is hitting dango
if (skewerPlayer.hitTestObject(currentDango))
{
//remove the current dango from stage
currentDango.destoryDango()
//Remove the dango from out dango array
aDangoArray.splice(i, 1);
//Add one to our score
nScore++;
updateScoreText();
}
}
}
// Remove the dango of the stage and from the array
private function checkDangosOffScreen():void
{
//loop through all our dangos(enemies)
for (var i:int = 0; i < aDangoArray.length; i++)
{
//Get our current dango in the loop
var currentDango:mcDango = aDangoArray[i];
//When dango starts on the top AND our curent enemy has gone past the bottom side if the stage
if (currentDango.y > (stage.stageHeight + currentDango.y / 2))
{
//Remove dango (enemy) from array
aDangoArray.splice(i, 1);
//Remove dango (enemy) from stage
currentDango.destoryDango();
}
}
}
private function clampPlayerToStage():void
{
//If our player is to the left of the stage
if (skewerPlayer.x < skewerPlayer.width/2)
{
//Set our player to left of the stage
skewerPlayer.x = skewerPlayer.width/2;
} else if (skewerPlayer.x > (stage.stageWidth - (skewerPlayer.width / 2)))
//If our player is to the right of the stage
{
//Set our player to right of the stage
skewerPlayer.x = stage.stageWidth - (skewerPlayer.width / 2);
}
//If our player is to the top(up) of the stage
if (skewerPlayer.y < 0)
{
//Set our player to the top(up) of the stage
skewerPlayer.y = 0;
} else if (skewerPlayer.y > (stage.stageHeight - (skewerPlayer.height / 1)))
//If our player is to the bottom(down) of the stage
{
//Set our player to the bottom(down) of the stage
skewerPlayer.y = stage.stageHeight - (skewerPlayer.height / 1);
}
}
// right, left, top and bottom Key Functions
private function playerContorl():void
{
//if our left key is currently down
if (leftKeyIsDown == true)
{
//move our player to the left
skewerPlayer.x -= 5;
}
//if our right key is currently down
if (rightKeyIsDown)
{
//move our player to the right
skewerPlayer.x += 5;
}
//if our up key is currently down
if (upKeyIsDown)
{
//move our player to the top
skewerPlayer.y -= 5;
}
//if our down key is currently down
if (downKeyIsDown)
{
//move our player to the bottom
skewerPlayer.y += 5;
}
}
private function keyUp(e:KeyboardEvent):void
{
//if our left key is released
if (e.keyCode == 37)
{
//left key is released
leftKeyIsDown = false;
}
//if our right key is released
if (e.keyCode == 39)
{
//right key is released
rightKeyIsDown = false;
}
//if our up key is released
if (e.keyCode == 38)
{
//up key is released
upKeyIsDown = false;
}
//if our down key is released
if (e.keyCode == 40)
{
//down key is released
downKeyIsDown = false;
}
}
private function keyDown(e:KeyboardEvent):void
{
//if our left key is pressed
if (e.keyCode == 37)
{
//left key is pressed
leftKeyIsDown = true;
}
//if our right key is pressed
if (e.keyCode == 39)
{
//right key is pressed
rightKeyIsDown = true;
}
//if our up key is pressed
if (e.keyCode == 38)
{
//up key is pressed
upKeyIsDown = true;
}
//if our down key is pressed
if (e.keyCode == 40)
{
//right key is pressed
downKeyIsDown = true;
}
}
}
}
---------------------------------------------------------------------------------
/*This is for mcDango doc */
package
{
import flash.display.MovieClip;
import flash.events.Event;
/**
* ...
* #author
*/
public class mcDango extends MovieClip
{
private var nSpeed:Number;
private var nRandom:Number;
public function mcDango()
{
// listen for when the Dango is added to the stage
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
init();
}
private function init():void
{ //Number of frames you have in Flash
var nDango:Number = 12;
//Pick random number between 1 and our number of enemies(dango)
var nRandom:Number = randomNumber(1, nDango)
//Setup our player of this enemey(dango) clip to pur random dango
this.gotoAndStop(nRandom);
//Setup our enemies(dango) start position
setupStartPosition();
}
private function setupStartPosition():void
{
//Pick a random speed for enemy(dango)
nSpeed = randomNumber(5, 10);
//Set your ramdon X postion
nRandom = randomNumber(9, 775);
//Start our enemy(dango) on the top side
this.y = -50;
//set random pos X
this.x = nRandom
//move our enmey(dango)
startMoving();
}
private function startMoving():void
{
addEventListener(Event.ENTER_FRAME, dangoLoop)
}
private function dangoLoop(e:Event):void
{
//Test what direction our enemy(dango) is moving in
//If our enemy(dango) is moving right
//Move our enemy(dango) down
this.y += nSpeed
}
public function destoryDango():void
{
//Remove dango from stage
parent.removeChild(this);
trace("the dango has been removed")
//Remove any event listeners in our enemy object
removeEventListener(Event.ENTER_FRAME, dangoLoop);
}
function randomNumber(low:Number=0, high:Number=1):Number
{
return Math.floor(Math.random() * (1+high-low)) + low;
}
}
}
Glancing at the code, looks like the problem is with following for-each-in loop
for each(var dango:mcDango in aDangoArray) {
//this destory function had to be removed as well. because it was destorying the dango twice when it was already removed from the stage.
//by commenting out this, it was able to destory and remove without any errors and only doing it once.
//Destory the dango the were curretly up to in the for loop
dango.destoryDango();
trace("black dango removed")
//Remove from dango from dango array
aDangoArray.splice(0, 1);
}
Check using
while(aDangoArray.length > 0) {
var dango = aDangoArray[0]
dango.destoryDango();
trace("black dango removed")
aDangoArray.splice(0, 1);
}
Well, it looks like the issue is when you try to access the parent.removeChild method. Maybe you already removed it from stage and it doesn't have a parent anymore. Try doing this:
public function destoryDango():void
{
//Remove dango from stage
if(parent != null)
parent.removeChild(this);
trace("the dango has been removed")
//Remove any event listeners in our enemy object
removeEventListener(Event.ENTER_FRAME, dangoLoop);
}