Objects to bounce around the screen? - actionscript-3

I would like to make the 5 'burger' objects bounce around the screen so they are harder to shoot as is the aim of my game. But, so far they are only lining up at the top of the stage so it's way too easy to play. Would I need to create 5 separate objects with 5 separate instance names etc.
This is what I have so far:
var firing:Boolean = false;
var bullet:Bullet1 = new Bullet1();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(event:KeyboardEvent):void {
switch(event.keyCode) {
case Keyboard.LEFT :
ball.x -= 10;
break;
case Keyboard.SPACE :
if (!firing) {
fire();
}
break;
case Keyboard.RIGHT :
ball.x += 10;
break;
case Keyboard.UP :
ball.y -= 10;
break;
case Keyboard.DOWN :
ball.y += 10;
break;
default :
break;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function fire() {
addChild(bullet);
firing = true;
bullet.x = ball.x;
bullet.y = ball.y - 60
;
}
addEventListener(Event.ENTER_FRAME, movestuff);
function movestuff(event:Event):void {
if (firing) {
bullet.y -= 20;
if (bullet.y < 0) {
firing = false;
removeChild(bullet);
}
}
}
var numBurger:Number = 5;
var array:Array = new Array();
for (var i:uint = 0; i<numBurger; i++) {
var burger:Burger = new Burger();
array.push(burger);
addChild(burger);
burger.x = 100 + 100*i;
burger.y = 50;
}
addEventListener(Event.ENTER_FRAME, checkCollision);
function checkCollision(event:Event)
{
for (var i:uint=0; i<array.length; i++)
{
if (array[i].hitTestObject(bullet))
{
removeChild(array[i]);
array.splice(i,1);
return;
}
}
}
Thanks for any help.

No, you would not have to create each movie clip separately if you use a loop to create randomized x and y locations for each burger. You can also use Math.random() to give a random speed and direction to each burger. In the code below these values are held in "direction_ary" array. This code creates five MovieClips of the "Burger"class, and places them at random points on the screen. The code also creates random speeds and directions for each MovieClip:
import flash.events.Event;
function find_random(max,min){
return Math.round(min+(max-min)*Math.random());
}
var ary:Array = [];
var direction_ary:Array = [];
for(var i:uint=0;i<5;i++){
ary[i]=new Burger();
ary[i].name="burger"+(i);
ary[i].x=find_random(stage.stageWidth-ary[i].width,ary[i].width);
ary[i].y=find_random(stage.stageHeight-ary[i].height,ary[i].height);
addChild(ary[i]);
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
for(var e:uint=0;e<100;e++){
if(direction_ary[i][0]==0||direction_ary[i][1]==0){
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
}else{
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME,update_burgers);
function update_burgers(e:Event){
for(var i:uint=0;i<5;i++){
if (ary[i].x>stage.stageWidth||ary[i].x<0){
direction_ary[i][0]*=-1;
}
if (ary[i].y>stage.stageHeight||ary[i].y<0){
direction_ary[i][1]*=-1;
}
ary[i].x+=direction_ary[i][0];
ary[i].y+=direction_ary[i][1];
}
}
The code is fairly self explanatory. Good luck with your project.
Cheers,
Drake Swartzy

Related

Having an issue with Flash Actionscript3

Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
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 sheep 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;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
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;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);

Flash As3 Variable Issue

I have a variable on frame 1 that starts at 3000 and keeps decreasing. This variable determines the gap of time between the spawn of an object. so basically the objects spawn quicker and quicker as the this number decreases. Everything works fine except the fact when i make the character die and the main timeline goes to frame 2 to show the death screen. When clicked "play again" on that frame that makes you come back to frame 1. the objects keep spawning at whatever speed they were spawning before death. Even though the variable resets to 3000 when "play again" clicked..
I traced the variable and it does truely reset. but for some reason those spawning objects follow the previous variable.
Heres the code on the first Frame:
import flash.events.Event;
stop();
var num1:Number = 0;
var scrollSpeed:Number = 3000;
var playerState:Number = 1;
var alive:Boolean = true;
var Redbars:Array = new Array();
var Bluebars:Array = new Array();
var scoreCount:Number = 10;
addEventListener(Event.ENTER_FRAME, update);
function update(e:Event){
trace(scrollSpeed);
scoreCount += 1;
scoreText.text = (scoreCount).toString();
//SCROLL SPEED-------------------
if(scrollSpeed > 300)
{
scrollSpeed -= 1;
}
//--------------------------------
CheckForCollisionBlue();
CheckForCollisionRed();
//trace(alive);
if(player.currentFrame == 1){
playerState = 1;
}
//Check if lost
if(player.hitTestObject(leftHitBox)){
gotoAndStop(2);
scoreEnd.text = (scoreCount).toString();
}
//If dead Delete Object
if(currentFrame == 2){
deleteBlue();
deleteRed();
}
}
////
//Timer////////////////////////////////
var myTimer:Timer = new Timer(scrollSpeed,10000000);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
//Generate Random number
num1 = randomRange();
trace(num1);
//IF NUM1 = 1------------------------------------------
if(num1 == 1){
//Create a Red Bar
var redBar = new Jump_Cube();
Redbars.push(redBar); //add enemy to the array
redBar.x = -33;
redBar.y = 99;
redBar.width = 12.5;
redBar.height = 20.45;
//Update the Bar
for(var i:int=0; i < Redbars.length; i++){
if(currentFrame == 1)
{
addChild(Redbars[i]);
}
}
}
//IF NUM1 = 2------------------------------------------
if(num1 == 2){
//Create a Blue Bar
var blueBar = new Jump_Cube2();
Bluebars.push(blueBar); //add enemy to the array
blueBar.x = -26.8;
blueBar.y = 10;
blueBar.width = 12.25;
blueBar.height = 31.90;
//Update the Bar
for(var j:int=0; j < Bluebars.length; j++){
if(currentFrame == 1)
{
addChild(Bluebars[j]);
}
}
myTimer.delay = scrollSpeed;
}
}
myTimer.start();
//--------------------------------------------------------------------
//Check for Collision------------------------------
function CheckForCollisionBlue(){
for(var i:int=0; i < Bluebars.length; i++){
if( player.hitTestObject(Bluebars[i]) ){
//Collision
trace("Didnt Hit Blue");
player.x -= 5;
player.y += 1;
}
}
}
//Check for Collision------------------------------
function CheckForCollisionRed(){
for(var i:int=0; i < Redbars.length; i++){
if( player.hitTestObject(Redbars[i]) ){
//Collision
trace("Didnt Hit Red");
player.x -= 5;
player.y += 1;
}
}
}
function randomRange():Number
{
return (Math.floor(Math.random() * (2 - 1 + 1)) + 1);
}
///////////BUTTONS------------------
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
redButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndRed);
function onTouchEndRed(e:TouchEvent):void{
player.gotoAndPlay(2);
playerState = 2;
}
blueButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndBlue);
function onTouchEndBlue(e:TouchEvent):void{
player.gotoAndPlay(19);
playerState = 3;
}
///////--CLEARING STAGE
//--------------------------------------------------------------------
//delete Blue------------------------------
function deleteBlue(){
for(var i:int=0; i < Bluebars.length; i++){
removeChild(Bluebars[i]);
}
}
//delete Red------------------------------
function deleteRed(){
for(var i:int=0; i < Redbars.length; i++){
removeChild(Redbars[i]);
}
}
Heres the code on the second frame:
stop();
alive = false;
againButton.addEventListener(TouchEvent.TOUCH_END, again);
function again(e:TouchEvent):void{
gotoAndStop(1);
playerState = 1;
scrollSpeed = 3000;
deleteBlue();
deleteRed();
}
You have to put in a removeEventListener(Event.ENTER_FRAME, update); inside your onTouchEndRed function. And probably also inside of this 'if' conditional: if(player.hitTestObject(leftHitBox)){...
Simply stop programming using frames. Use classes instead. AS3 is based on classes. It'll take you a lot of benefits. This link may help you to start: http://www.adobe.com/devnet/actionscript/getting_started.html
Additionally, FlashPlayer executes frame's code each time you jump to another frame. Thats why your variables are reinitializing.

Level progression in a platform game? (Actionscript 3)

I've been working on a Platformer for a couple of weeks now and i can't seem to get the level progression working. I'm using a basic hitTest on a box to signal the movement from frame 1(level 1) to frame 2 (level 2) but once the character hits the exit box, i get the following error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LevelProg_fla::MainTimeline/loop()
What can i do so that it moves to the next frame(level)? If it helps, my code is in a frame rather than a class. Basically, the only code that i'm using for level progression is
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
with "levelTwo" being the name of the next frame (next level). The rest of the game's code is as follows (pardon the messyness of it, I've been more focused on getting the darn thing to work :b)
import flash.events.KeyboardEvent;
import flash.events.Event;
//some variables to track the player's speed
var speedX = 0;
var speedY = 0;
player.height = 80.0;
player.width = 60.0;
//loop through all the platform objects to generate the level
var level:Array = new Array();
for (var i=0; i<numChildren; i++)
{
if (getChildAt(i) is platform)
{
level.push(getChildAt(i).getRect(this));
}
}
//make variables to store key states
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
//listen for key presses and releases
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=true;
if (k.keyCode==38) kUp=true;
if (k.keyCode==39) kRight=true;
if (k.keyCode==40) kDown=true;
}
function kU(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=false;
if (k.keyCode==38) kUp=false;
if (k.keyCode==39) kRight=false;
if (k.keyCode==40) kDown=false;
}
//Make a looping function
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
//lateral movement checks
if (kLeft)
{
speedX=-10;
}
else if (kRight)
{
speedX=10;
}
else
{
speedX*=0.5; //friction to slow player down (kinda like mario)
}
//does not stop the character
//move player based on the above
player.x+=speedX;
//animations
if (speedX > 0)
{
trace("right pressed");
//player.gotoAndPlay("walkRight");
}
if (speedX < 0)
{
trace("left pressed");
//player.gotoAndPlay("walkLeft");
}
//sidewards hit tests
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedX > 0) ////moving right collision and stuffs
{
player.x = level[i].left-player.width/2;
}
if (speedX < 0) ////moving left collision and stuffs
{
player.x = level[i].right+player.width/2;
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//vertical checks
speedY+=1;
player.y+=speedY;
var jumpable = false
//vertical hitTests
//note that it's the same as the x code but just changed like 5 things.
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedY > 0) ////moving down collision and stuffs
{
player.y = level[i].top-player.height/2;
speedY=0;
jumpable = true;
}
if (speedY < 0) ////moving up collision and stuffs
{
player.y = level[i].bottom+player.height/2;
speedY*=-0.5; //bounces off cielings
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//jumps if possible
if (kUp && jumpable)
{
speedY=-15;
}
//gravity might help}
//move player with camera function/code/script/tired
this.x=-player.x+(stage.stageWidth/2); //centers the player
this.y=-player.y+(stage.stageWidth/2); //centers the player
//Progresses the player to level 2
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
}

How do I get velocity for my character in as3

im trying to make a teleporter game and my character needs to have some velocity and gravity, does anyone know what sums i need to be able to acomplish this?
This is my code so far:
var char = this.addChild(new Char());
char.width = 20;
char.height = 20;
char.x = startPos.x; //startPos is an invisible movieclip that I can move around to make the starting position
char.y = startPos.y; // accurate
var vx:Number = 0;
var vt:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyDownHandler (e:KeyboardEvent):void {
switch (e.keyCode) {
case Keyboard.UP:
char.y = char.y - 5
}
}
If your char only needs to go up then the following code will do the job.
But if it needs to move in all direction then much advanced code is required.
Follow Moving Character in all directions.
This is a quick solution to your need.
var gravity:Number = 2;
var velocity:Number = 1.1;
var move:Boolean = false;
function moveChar(e:Event):void
{
if(move)
{
gravity *= velocity;
char.y -= gravity; // move char
}
}
char.addEventListener(Event.ENTER_FRAME, moveChar, false, 0, true);
//Keyboard events
function keyDownHandler (e:KeyboardEvent):void
{
switch (e.keyCode)
{
case Keyboard.UP:
move = true;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyUpHandler (e:KeyboardEvent):void
{
move = false;
gravity = 2;
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

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

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