boundares - if object is past, delete object - actionscript-3

I have a code below that has rocks moving from left to right, I would like to create a boundary for them that they can only move a certain way in on the stage, once they get past this point they delete. I have tried to write this up under the Wrap Rocks and Delete Rocks section, but it's not working and it's not giving me any errors. Does anyone have any thoughts that might help me?
let me know if you need to see more code:
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
public class SpaceRocks_v002 extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .02;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
// start the game
public function startSpaceRocks_v002():void {
// set up sprites
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
addEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// start
gameMode = "delay";
shieldOn = false;
missiles = new Array();
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 20+i*15;
newShip.y = 375;
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 530-i*15;
newShield.y = 375;
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
scoreDisplay = new TextField();
scoreDisplay.x = 480;
scoreDisplay.y = 100;
scoreDisplay.width = 20;
scoreDisplay.selectable = false;
var scoreDisplayFormat = new TextFormat();
scoreDisplayFormat.color = 0xFFFFFF;
scoreDisplayFormat.font = "Arial";
scoreDisplayFormat.align = "right";
scoreDisplayFormat.size = 15;
scoreDisplay.defaultTextFormat = scoreDisplayFormat;
scoreObjects.addChild(scoreDisplay);
updateScore();
}
// new score to show
public function updateScore() {
scoreDisplay.text = String(gameScore);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 400;
ship.y = 350;
ship.rotation = -180;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
}
}
// register key presses
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = true;
} else if (event.keyCode == 40) {
rightArrow = true;
} else if (event.keyCode == 32) { // space
newMissile();
} else if (event.keyCode == 90) { // z
startShield(false);
}
}
// register key ups
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = false;
} else if (event.keyCode == 40) {
rightArrow = false;
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
if (leftArrow) {
ship.y -= 2;
} else if (rightArrow) {
ship.y+= 2;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// check boundaries
if (ship.y < 65) ship.y = 65;
if (ship.y > 380) ship.y = 380;
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
removeAllShieldIcons();
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 20;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 10;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3+1));
// set start position
newRock.x = Math.random()*0;
newRock.y = Math.random()*280+80;
// set random movement and rotation
var dx:Number = Math.random()*3;
var dy:Number = Math.random()*2;
// add to stage and to rocks list
gameObjects.addChild(newRock);
rocks.push({rock:newRock, dx:dx, dy:dy, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(100,1,"Big");
newRock(200,1,"Big");
newRock(450,1,"Big");
newRock(350,1,"Big");
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += rocks[i].dy*rockSpeed;
// wrap rocks
if ((rocks[i].rock.x > 0) && (x <-50)) {
deleteRocks();
}
else if ((rocks[i].rock.x < 0) && (x > 50)) {
deleteRocks();
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
}
// remove original rock
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
public function deleteRocks(){
gameMode = "delay";
newRock.gotoAndPlay("bang");
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 550) || (missiles[i].y < 0) || (missiles[i].y > 400)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gotoAndStop("gameover");
}
}
}
thanks in advance for the help!!

first pass out the rock you want to delete
deleteRocks(rocks[i].rock);
then remove it from the stage
public function deleteRocks(rock){
gameMode = "delay";
trace("Rock Deleted");
gameObjects.removeChild(rock) ;
}
But I think there is a problem with your if condition that control the removing of rocks. check it out

Related

How can I change Nested Class in actionscript 3

I'm working off an actionscript 3 code that pulls information from other actionscript 3's. The main code is Herbfight and it references 4 others (Bullets, bugs, Goodbugs and Sprayer). Below I'm trying to combine them all into one actionscript. The reason for this is that I want to pull it in as a symbol rather then having the flash file relate to the class.
The problem is it says I can't have nested classes. Any thoughts on how i can fix this? Below is my attempt to combine the code.
Thanks,
J
package {
import flash.display.;
import flash.events.;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.*;
import flash.utils.getTimer;
import flash.geom.Point;
public class herbfight_v004 extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var goodbug:Array;
private var bullets:Array;
private var upArrow, downArrow:Boolean;
private var nextPlane:Timer;
private var nextGbugs:Timer;
private var shotsLeft:int;
private var shotsHit:int;
private var Sprayer:MovieClip
private var Bullets:MovieClip
private var bugs:MovieClip
private var GooodBugs:MovieClip
public function startherbfight_v004() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
airplanes = new Array();
bullets = new Array();
goodbug = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbugs();
public function Sprayer() {
{
// animation time// initial location of gun
this.x = 410;
this.y = 380;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
public function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newy = this.y;
// move to the left
if (MovieClip(parent).upArrow) {
newy -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).downArrow) {
newy += speed*timePassed/1000;
}
// check boundaries
if (newy < 65) newy = 65;
if (newy > 380) newy = 380;
// reposition
this.y = newy;
}
// remove from screen and remove events
public function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
public function bugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
public function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
// plane hit, show explosion
public function planeHit() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
gotoAndPlay("explode");
}
// delete plane from stage and plane list
public function deletePlane() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
parent.removeChild(this);
}
}
public function Bullets(x,y:Number, speed: Number) {
{
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
public function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
public function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
public function GoodBugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = -1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = -1; // not reverse
}
this.y = altitude; // vertical position
// choose a random Gbugs
this.gotoAndStop(Math.floor(Math.random()*2+1));
// set up animation
addEventListener(Event.ENTER_FRAME,moveGbugs);
lastTime = getTimer();
}
public function moveGbugs(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move Gbugs
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deleteGbugs();
} else if ((dx > 0) && (x > 350)) {
deleteGbugs();
}
}
// Gbugs hit, show explosion
public function GbugsHit() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
gotoAndPlay("explode");
}
// delete Gbugs from stage and Gbugs list
public function deleteGbugs() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
parent.removeChild(this);
}
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbugs() {
nextGbugs = new Timer(1000+Math.random()*1000,1);
nextGbugs.addEventListener(TimerEvent.TIMER_COMPLETE,newGbugs);
nextGbugs.start();
}
public function newGbugs(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create Gbugs
var p:GoodBugs = new GoodBugs(side,speed,altitude);
addChild(p);
goodbug.push(p);
// set time for next Gbugs
setNextGbugs();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var GoodBugsNum:int= goodbug.length-1; GoodBugsNum>=0; GoodBugsNum--) {
if (bullets[bulletNum].hitTestObject(goodbug [GoodBugsNum])) {
goodbug [GoodBugsNum]. GbugsHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = true;
} else if (event.keyCode == 40) {
downArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = false;
} else if (event.keyCode == 40) {
downArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a plane from the array
public function removeGbugs(Gbugs:GoodBugs) {
for(var i in goodbug) {
if (goodbug[i] == Gbugs) {
goodbug.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int= goodbug.length-1;i>=0;i--) {
goodbug [i].deleteGbugs();
}
airplanes = null;
goodbug = null
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbugs.stop();
nextGbugs = null;
gotoAndStop("gameover");
}
}
}

Errors on end game on score

OK I"ve managed to fix most of the error, the main remaining ones are when I try to make the game end when it hits 50... This is now the error I get and when I go into the next level the ship disappears, but the game plays with an invisible ship....
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at SpaceRocks_v008/newShip()[/Users/Jess/Documents/UNI/INFT6303_game_design/Ass_3/Flash_V2/SpaceRocks_v008.as:168]
at SpaceRocks_v008/startSpaceRocks_v008()[/Users/Jess/Documents/UNI/INFT6303_game_design/Ass_3/Flash_V2/SpaceRocks_v008.as:84]
at SpaceRocks_v008/frame2()
Cannot display source code at this location.
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
public class SpaceRocks_v008 extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .02;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore1:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
// start the game
public function startSpaceRocks_v008() {
// set up sprites
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore1 = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
addEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// start
gameMode = "delay";
shieldOn = false;
missiles = new Array();
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 460+i*30;
newShip.y = 328;
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 520-i*30;
newShield.y = 210;
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
scoreDisplay = new TextField();
scoreDisplay.x = 460;
scoreDisplay.y = 68;
scoreDisplay.width = 40;
scoreDisplay.selectable = false;
var scoreDisplayFormat = new TextFormat();
scoreDisplayFormat.color = 0xFFFFFF;
scoreDisplayFormat.font = "Arial";
scoreDisplayFormat.align = "right";
scoreDisplayFormat.size = 15;
scoreDisplay.defaultTextFormat = scoreDisplayFormat;
scoreObjects.addChild(scoreDisplay);
updateScore();
}
// new score to show
public function updateScore() {
scoreDisplay.text = String(gameScore1);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
//upper scrore reached
if (gameScore1 >= 50) {
trace("high")
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 400;
ship.y = 350;
ship.rotation = -180;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
}
}
// register key presses
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = true;
} else if (event.keyCode == 40) {
rightArrow = true;
} else if (event.keyCode == 32) { // space
newMissile();
} else if (event.keyCode == 37) { // left arrow
startShield(false);
}
}
// register key ups
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
leftArrow = false;
} else if (event.keyCode == 40) {
rightArrow = false;
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
// rotate and thrust
if (leftArrow) {
ship.y -= 2;
} else if (rightArrow) {
ship.y+= 2;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// wrap around screen
if (ship.y < 65) ship.y = 65;
if (ship.y > 380) ship.y = 380;
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
removeAllShieldIcons();
delayTimer = new Timer(1000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 30;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 25;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3));
// set start position
newRock.x = Math.random()*0;
newRock.y = Math.random()*280+80;
// set random movement and rotation
var dx:Number = Math.random()*3;
var dy:Number = Math.random()*2;
// add to stage and to rocks list
gameObjects.addChild(newRock);
rocks.push({rock:newRock, dx:dx, dy:dy, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(100,1,"Big");
newRock(200,1,"Big");
newRock(450,1,"Big");
newRock(350,1,"Big");
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += 0
// wrap rocks
if ((rocks[i].rock.x) > 400){
deleteRocks(i);
}
else if ((rocks[i].rock.y) > 401){
deleteRocks(i);
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
} else if (rocks[rockNum].rockType == "Medium") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
}
// remove original rock
rocks[rockNum].rock.gotoAndPlay("bang");
//gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
public function deleteRocks(rockNum:uint) {
//remove rock from game
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 550) || (missiles[i].y < 0) || (missiles[i].y > 400)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore1 += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
if (gameScore1 >= 50) {
shipsLeft = 0;
if (shipsLeft < 1) {
endGame();
return;
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gotoAndStop("gameover");
}
}
}

AS3 Frogger Pixel Perfect Collision

I have created a simple AS3 frogger game and used .hitTestObject to test if the frog hits any of the obstacles. This is not effective as the frog hits objects that aren't touching it at all. I am new to AS3 and have no idea where to start with coding for this. Any help would be appreciated!
package {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.utils.Timer;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class Main extends MovieClip
{
//set variables
public var frog_spriteInstance:frog_sprite;
public var safeZoneInstance1 : safeZone;
public var safeZoneInstance2: safeZone;
public var safeZoneInstance3 : safeZone;
public var whitecar : car1;
public var whitecar1 : car1;
public var whitecar2 : car1;
public var truck1 : truck_sprite;
public var truck2: truck_sprite;
public var redcar : car_sprite;
public var redcar2 : car_sprite;
public var redcar3 : car_sprite;
public var log1 : log_sprite;
public var log2 : log_sprite;
public var log3 : log_sprite;
public var letters : Letters;
public var letters2 : Letters_2;
public var letters3 : Letters_3;
public var letters4 : Letters_4;
public var health : HealthBar;
public var firstletter : firstLetter;
public var secondletter : secondLetter;
public var thirdletter : thirdLetter;
public var fourthletter : fourthLetter;
var mysound:Sound = new (mySound);
public function Main()
{
// constructor code
safeZoneInstance1 = new safeZone();
stage.addChild(safeZoneInstance1);
safeZoneInstance1.x = 300;
safeZoneInstance1.y=545
safeZoneInstance2 = new safeZone();
stage.addChild(safeZoneInstance2);
safeZoneInstance2.x = 300;
safeZoneInstance2.y=300
safeZoneInstance3 = new safeZone();
stage.addChild(safeZoneInstance3);
safeZoneInstance3.x = 300;
safeZoneInstance3.y=100
whitecar = new car1();
stage.addChild(whitecar);
whitecar.x = 300;
whitecar.y = 500
whitecar1 = new car1();
stage.addChild(whitecar1);
whitecar1.x = 550;
whitecar1.y = 480
whitecar2 = new car1();
stage.addChild(whitecar2);
whitecar2.x = 50;
whitecar2.y = 480
truck1 = new truck_sprite();
stage.addChild (truck1);
truck1.x = 1000;
truck1.y = 430
truck2 = new truck_sprite();
stage.addChild (truck2);
truck2.x = 300;
truck2.y = 430
redcar = new car_sprite();
stage.addChild (redcar);
redcar.x = 300;
redcar.y = 340
redcar2 = new car_sprite();
stage.addChild (redcar2);
redcar2.x = 100;
redcar2.y = 375
redcar3 = new car_sprite();
stage.addChild (redcar3);
redcar3.x = 500;
redcar3.y = 375
log1 = new log_sprite();
stage.addChild(log1);
log1.x = 300;
log1.y = 230
log2 = new log_sprite();
stage.addChild(log2);
log2.x = 100;
log2.y = 150
log3 = new log_sprite();
stage.addChild(log3);
log3.x = 500;
log3.y = 150
letters = new Letters();
letters.x = randomRange(100,500) ;
letters.y = randomRange(100,500);
stage.addChild(letters);
letters2 = new Letters_2();
letters2.x = randomRange(100,500) ;
letters2.y = randomRange(100,500);
stage.addChild(letters2);
letters3 = new Letters_3();
letters3.x = randomRange(100,500) ;
letters3.y = randomRange(100,500);
stage.addChild(letters3);
letters4 = new Letters_4();
letters4.x = randomRange(100,500) ;
letters4.y = randomRange(100,500);
stage.addChild(letters4);
frog_spriteInstance = new frog_sprite();
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
health = new HealthBar();
stage.addChild(health);
health.x = 130;
health.y = 20;
health.width = 100;
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.addEventListener(Event.ENTER_FRAME, movecars);
stage.addEventListener(Event.ENTER_FRAME, movetrucks);
stage.addEventListener(Event.ENTER_FRAME, moveredcars);
stage.addEventListener(Event.ENTER_FRAME, movelogs);
stage.addEventListener(Event.ENTER_FRAME,checkforcollision);
mysound.play();
}
public function moveFrog(e:KeyboardEvent)
{
// get the key pressed and then move the player
{
if (e.keyCode == Keyboard.UP)
{
frog_spriteInstance.rotation = 0;
frog_spriteInstance.y -= 50;
}
if (e.keyCode == Keyboard.DOWN)
{
frog_spriteInstance.rotation = 180;
frog_spriteInstance.y += 50;
}
if (e.keyCode == Keyboard.LEFT)
{
frog_spriteInstance.rotation = -90;
frog_spriteInstance.x -= 50;
}
if (e.keyCode == Keyboard.RIGHT)
{
frog_spriteInstance.rotation = 90;
frog_spriteInstance.x += 50;
}
}
}
function movecars(event:Event)
{
//move cars across screen and when they disappear, reappear at the other side
whitecar.x -= 3;
if (whitecar.x<-100){
whitecar.x=650;
}
whitecar1.x -= 3;
if (whitecar1.x<-100){
whitecar1.x=650;
}
whitecar2.x -= 3;
if (whitecar2.x<-100){
whitecar2.x=650;
}
}
function movelogs(event:Event)
{
//move logs across screen and when they disappear, reappear at the other side
log1.x -= 5;
if (log1.x<-100){
log1.x=650;
}
log2.x -= 5;
if (log2.x<-100){
log2.x=650;
}
log3.x -= 5;
if (log3.x<-100){
log3.x=650;
}
}
function movetrucks(event:Event)
{
//move trucks across screen and when they disappear, reappear at the other side
truck1.x +=3;
if (truck1.x>650){
truck1.x=-100;
}
truck2.x +=3;
if (truck2.x>650){
truck2.x=-100;
}
}
function moveredcars(event:Event)
{
//move red cars across screen and when they disappear, reappear at the other side
redcar.x +=3;
if (redcar.x>650){
redcar.x=-100;
}
redcar2.x +=3;
if (redcar2.x>650){
redcar2.x=-100;
}
redcar3.x +=3;
if (redcar3.x>650){
redcar3.x=-100;
}
}
function checkforcollision(event:Event)
{
//check for collisions
if (frog_spriteInstance.hitTestObject(log1) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(log3) || (frog_spriteInstance.hitTestObject(whitecar) || (frog_spriteInstance.hitTestObject(whitecar1) || (frog_spriteInstance.hitTestObject(whitecar2) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(truck1) || (frog_spriteInstance.hitTestObject(truck2) || (frog_spriteInstance.hitTestObject(redcar) || (frog_spriteInstance.hitTestObject(redcar2) || (frog_spriteInstance.hitTestObject(redcar3))))))))))))){
//reset frog if hits an obstacle
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
//reduce health bar
health.width -= 10;
}
//remove event listeners when health is empty
if (health.width == 0){
stage.removeEventListener(Event.ENTER_FRAME, movecars);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.removeEventListener(Event.ENTER_FRAME, movetrucks);
stage.removeEventListener(Event.ENTER_FRAME, moveredcars);
stage.removeEventListener(Event.ENTER_FRAME, movelogs);
}
//add letters to bottom of screen when hit correctly
if (frog_spriteInstance.hitTestObject(letters)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters);
firstletter = new firstLetter();
stage.addChild(firstletter);
firstletter.x=345;
firstletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters2)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters2);
secondletter = new secondLetter();
stage.addChild(secondletter);
secondletter.x=206;
secondletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters3)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters3);
thirdletter = new thirdLetter();
stage.addChild(thirdletter);
thirdletter.x=273;
thirdletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters4)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters4);
health.width -= 10;
fourthletter = new fourthLetter();
stage.addChild(fourthletter);
fourthletter.x=25;
fourthletter.y=620;
}
}
function randomRange(minNum:Number, maxNum:Number):Number
{
//random generator for letter positioning
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
}
}
Also my code is pretty dodgy so any suggestions on improvement are very welcome.
To perform pixel perfect hit test from two arbitrary display objects you have to draw them to bitmaps and use BitmapData/hitTest().
Here is a generalized function that does this:
function hitTestShapes(object1:DisplayObject, object2:DisplayObject, threshold:uint = 1):Boolean {
var bounds1:Rectangle = object1.getBounds(object1.parent);
var matrix1:Matrix = object1.transform.matrix;
matrix1.tx = object1.x - bounds1.x;
matrix1.ty = object1.y - bounds1.y;
var bmp1:BitmapData = new BitmapData(bounds1.width, bounds1.height, true, 0);
bmp1.draw(object1, matrix1);
var bounds2:Rectangle = object2.getBounds(object2.parent);
var matrix2:Matrix = object2.transform.matrix;
matrix2.tx = object2.x - bounds2.x;
matrix2.ty = object2.y - bounds2.y;
var bmp2:BitmapData = new BitmapData(bounds2.width, bounds2.height, true, 0);
bmp2.draw(object2, matrix2);
return bmp1.hitTest(bounds1.topLeft, threshold, bmp2, bounds2.topLeft, threshold);
}
Note, though, that drawing to bitmaps is rather slow, so be careful not to over-use this kind of function or you will have performance issues. In fact, it would be a good idea to use hitTestObject() first, which is very fast and detects bounding box intersections, then only call hitTestShapes() to refine your check. In other words:
if (frog_spriteInstance.hitTestObject(log1) && hitTestShapes(frog_spriteInstance, log1)) { }
As for suggestions on your code, there's a lot of potential for de-duplicating by way of arrays, loops, and functions. For example, instead of defining all your objects as separate variables, just store them all in an array (or vector):
public var safeZones:Array = [];
public var obstacles:Array = [];
public var letters:Array = [];
To populate the arrays, you can push values into them and use a function to consolidate all your duplicate object setup code:
(Code convention note: use "UpperCamelCase" for class names.)
public function Main(){
addSafeZone(300, 545);
addSafeZone(300, 300);
addSafeZone(300, 100);
addObstacle(WhiteCar, 300, 500);
addObstacle(WhiteCar, 550, 480);
addObstacle(WhiteCar, 50, 480);
addObstacle(Truck, 1000, 430);
addObstacle(Truck, 300, 430);
addObstacle(RedCar, 300, 340);
addObstacle(RedCar, 100, 375);
addObstacle(RedCar, 500, 375);
addObstacle(Log, 300, 230);
addObstacle(Log, 100, 150);
addObstacle(Log, 500, 150);
addRandomLetters(Letters_1);
addRandomLetters(Letters_2);
addRandomLetters(Letters_3);
addRandomLetters(Letters_4);
}
private function addSafeZone(x:Number, y:Number):void {
var safeZone:SafeZone = new SafeZone();
stage.addChild(safeZone);
safeZone.x = x;
safeZone.y = y
safeZones.push(safeZone);
}
private function addObstacle(spriteClass:Class, x:Number, y:Number):void {
var obstacle:Sprite = new spriteClass();
stage.addChild(obstacle);
obstacle.x = x;
obstacle.y = y
obstacles.push(obstacle);
}
private function addRandomLetters(lettersClass:Class):void {
var lettersSprite:Sprite = new lettersClass();
lettersSprite.x = randomRange(100, 500);
lettersSprite.y = randomRange(100, 500);
stage.addChild(lettersSprite);
letters.push(lettersSprite);
}
Now you can loop over the arrays to perform all your actions. For example, to check for a hit against any obstacle:
for each(var obstacle:DisplayObject in obstacles){
if(frog.hitTestObject(obstacle) && hitTestShapes(frog, obstacle)){
// The frog hit an obstacle!
}
}
You could also combine all our "move" functions into one, which moves each obstacle based on their type:
private function moveObstacles(e:Event):void {
for each(var obstacle in obstacles){
if(obstacle is WhiteCar){
obstacle.x -= 3;
}
else if(obstacle is RedCar){
obstacle.x += 3;
}
else if(obstacle is Truck){
obstacle.x += 3;
}
else if(obstacle is Log){
obstacle.x -= 5;
}
if(obstacle.x < -100){
obstacle.x = 650;
}
else if(obstacle.x > 650){
obstacle.x = -100;
}
}
}
Lastly, you really should only need a single ENTER_FRAME handler. Just call whatever functions you want from in there. Adding multiple ENTER_FRAME handlers can get troublesome to manage. For example, just do this:
addEventListener(Event.ENTER_FRAME, update);
private function update(e:Event):void {
moveObstacles();
doOtherStuff();
anythingYouNeedToDo();
}
This way you only need to removeEventListener(Event.ENTER_FRAME, update) to stop the game, not a whole bunch of ENTER_FRAME handlers.
I haven't tested any of this code, but you get the general idea. Let me know if you have any issues with it and I can help.

ActionScript 3 Cant see Movieclip

When I play my game it does not show my _Player Movieclip, but it does collide with the ground which is very confusing. So I believe the movieclip is there but not showing the texture/Sprite.
I think the problem is in "function Spawn" (First Function).
public class PewdyBird extends MovieClip
{
//Player variables
public var Up_Speed:int = 25;
public var speed:Number = 0;
public var _grav:Number = 0.5;
public var isJump:Boolean = false;
public var Score:int = 0;
public var Player_Live:Boolean = true;
public var _Player:Player = new Player();
//Other variables
//Environment variables
var Floor:int = 480;
var Clock:Number = 0;
var Clock_restart:Number = 0;
var Clock_ON:Boolean = false;
var Clock_max:int = 15;
var Player_Stage:Boolean = true;
private var _X:int;
private var _Y:int;
private var hit_ground:Boolean = false;
private var width_BG:int = 479;
//SPAWN
function Spawn(e:Event){
_Player.x = 200;
_Player.y = 200;
stage.addChild(_Player);
}
//Keyboard Input
private function KeyboardListener(e:KeyboardEvent){
if(e.keyCode == Keyboard.SPACE){
Clock = Clock_restart;
Clock_ON = true;
isJump = true;
if(isJump){
_Player.gotoAndPlay("Fly");
speed = -Up_Speed;
isJump = false;
}
}
}
//Mouse Input & Spawn Listener
private function MouseListener(m:MouseEvent){
if(MouseEvent.CLICK){
Clock = Clock_restart;
Clock_ON = true;
isJump = true;
if(isJump){
_Player.gotoAndPlay("Fly");
speed = -Up_Speed;
isJump = false;
}
}
}
//Rotation Fly
function Rot_Fly(){
if(Clock < Clock_max){
_Player.rotation = -15;
}else if(Clock >= Clock_max){
if(_Player.rotation < 90){
_Player.rotation += 10;
}else if(_Player.rotation >= 90){
_Player.rotation = 90;
}
}
}
//END
//Update Function
function enter_frame(e:Event):void{
Rot_Fly();
//Clock
if(Clock_ON){
Clock++;
}else if(Clock > Clock_max){
Clock = Clock_max;
}
//Fall Limits
if(speed >= 20){
_Player.y += 20;
return;
_Player.gotoAndPlay("Fall");
}
//Physics
speed += _grav*3;
_Player.y += speed;
}
//Hit Ground
function Hit_Ground(e:Event){
if(_Player.hitTestObject(Ground1)){
_grav = 0;
speed = 0;
trace("HIT GROUND");
}else if(_Player.hitTestObject(Ground2)){
_grav = 0;
speed = 0;
trace("HIT GROUND");
}else if(_Player.hitTestObject(Ground1) == false){
_grav = 1;
}else if(_Player.hitTestObject(Ground2) == false){
_grav = 1;
}
}
//Background Slide (Left)
private function Background_Move(e:Event):void{
Background1.x -= 1.5;
Background2.x -= 1.5;
Ground1.x -= 4;
Ground2.x -= 4;
if(Background1.x < -width_BG){
Background1.x = width_BG;
} else if(Background2.x < -width_BG){
Background2.x = width_BG;
} else if(Ground1.x < -width_BG){
Ground1.x = width_BG;
} else if(Ground2.x < -width_BG){
Ground2.x = width_BG;
}
}
}
The eventListeners are in flash it self
stage.addEventListener(Event.ENTER_FRAME, enter_frame);
stage.addEventListener(Event.ENTER_FRAME, Hit_Ground);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardListener);
stage.addEventListener(MouseEvent.CLICK, MouseListener);
stage.addEventListener(Event.ENTER_FRAME, Background_Move);
stage.addEventListener(Event.ADDED_TO_STAGE, Spawn);
Player.as
package
{
import flash.display.MovieClip;
public class Player extends MovieClip
{
public function Player()
{
super();
}
}
}
Check if the movie clip's class in the library (AS3 linkage) matches the name of your player class. Also, if PewdyBird is your document class, you can move the ADDED_TO_STAGE event in the constructor. Something, like:
public function PedwyBird() {
if (stage) {
initStage();
} else {
addEventListener(Event.ADDED_TO_STAGE, initStage);
}
}
And then you can call the spawn function in the initStage function, along with adding all the event listeners. You could also have one enter frame function instead of three.
private function initStage(e:Event = null){
Spawn(); //of course, you have to remove the e:Event from Spawn declaration
stage.addEventListener(Event.ENTER_FRAME, enter_frame);
stage.addEventListener(Event.ENTER_FRAME, Hit_Ground);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardListener);
stage.addEventListener(MouseEvent.CLICK, MouseListener);
stage.addEventListener(Event.ENTER_FRAME, Background_Move);
}

AS3 - Game Timer not calculating start time properly

I'm building a game in AS3 based off of Gary Rosenzweig's latest Actionscript 3 book. It has a game timer issue, not just mine but his demo too, that I can't figure out.
The game is like Asteroids where four rocks are placed in the corners of the stage at the beginning and then start moving randomly around the stage. The problem is the timer used is started the moment that the flash file starts not the moment the player clicks the start button. So if you are on the start screen for 5 seconds before you click play when the game actually begins the rocks are where they would be after 5 seconds of play, which could be right over the player.
I've posted the parts of the code that I think apply. Could someone please tell me how to modify this so that when the player actually starts the game the rocks start in their proper places. I'm pretty sure it's the last function that I've included that is the problem but I've included other related parts to give you a more complete picture.
package {
import flash.display.*;
import flash.events.*;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.geom.Point;
import flash.net.SharedObject;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.media.SoundChannel;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
public class VirusDefender extends MovieClip {
static const shipRotationSpeed:Number = .1;
static const rockSpeedStart:Number = .03;
static const rockSpeedIncrease:Number = .01;
static const missileSpeed:Number = .2;
static const thrustPower:Number = .15;
static const shipRadius:Number = 20;
static const startingShips:uint = 3;
// game objects
private var ship:Ship;
private var rocks:Array;
private var missiles:Array;
// animation timer
private var lastTime:uint;
// arrow keys
private var rightArrow:Boolean = false;
private var leftArrow:Boolean = false;
private var upArrow:Boolean = false;
// ship velocity
private var shipMoveX:Number;
private var shipMoveY:Number;
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
// game mode
private var gameMode:String;
private var shieldOn:Boolean;
// ships and shields
private var shipsLeft:uint;
private var shieldsLeft:uint;
private var shipIcons:Array;
private var shieldIcons:Array;
private var scoreDisplay:TextField;
// score and level
private var gameScore:Number;
private var gameLevel:uint;
// sprites
private var gameObjects:Sprite;
private var scoreObjects:Sprite;
var gameBackground:GameBackground = new GameBackground();
// sounds
var sndFire:fire_sound;
var sndFireChannel:SoundChannel;
var sndThruster:thruster_sound;
var sndThrusterChannel:SoundChannel;
var sndShield:shield_sound;
var sndShieldChannel:SoundChannel;
var sndExplosion:explosion_sound;
var sndExplosionChannel:SoundChannel;
var sndBubble:bubble_sound;
var sndBubbleChannel:SoundChannel;
// start the game
public function startSpaceRocks() {
// set up sprites
addChild(gameBackground);
setChildIndex(gameBackground,0); // I added this
gameObjects = new Sprite();
addChild(gameObjects);
scoreObjects = new Sprite();
addChild(scoreObjects);
// reset score objects
gameLevel = 1;
shipsLeft = startingShips;
gameScore = 0;
createShipIcons();
createScoreDisplay();
// set up listeners
trace("add moveGameObjects event listener");
addEventListener(Event.ENTER_FRAME,moveGameObjects);
leftButton.addEventListener(TouchEvent.TOUCH_OVER,leftPress);
leftButton.addEventListener(TouchEvent.TOUCH_OUT,leftRelease);
rightButton.addEventListener(TouchEvent.TOUCH_OVER,rightPress);
rightButton.addEventListener(TouchEvent.TOUCH_OUT,rightRelease);
thrusterButton.addEventListener(TouchEvent.TOUCH_OVER,thrusterPress);
thrusterButton.addEventListener(TouchEvent.TOUCH_OUT,thrusterRelease);
shieldButton.addEventListener(TouchEvent.TOUCH_OVER,shieldPress);
fireButton.addEventListener(TouchEvent.TOUCH_OVER,firePress);
// Left Button
function leftPress(event:TouchEvent):void{
leftArrow = true;
}
function leftRelease(event:TouchEvent):void{
leftArrow = false;
}
// Right button
function rightPress(event:TouchEvent):void{
rightArrow = true;
}
function rightRelease(event:TouchEvent):void{
rightArrow = false;
}
// Thruster button
function thrusterPress(event:TouchEvent):void{
sndThruster=new thruster_sound();
sndThrusterChannel=sndThruster.play();
upArrow = true;
if (gameMode == "play") ship.gotoAndStop(2);
}
function thrusterRelease(event:TouchEvent):void{
sndThrusterChannel.stop();
upArrow = false;
if (gameMode == "play") ship.gotoAndStop(1);
}
// Fire button
function firePress(event:TouchEvent):void{
sndFire=new fire_sound();
sndFireChannel=sndFire.play();
newMissile();
}
// Shield button
function shieldPress(event:TouchEvent):void{
startShield(false);
}
// start
gameMode = "delay";
trace("gameMode - delay");
shieldOn = false;
missiles = new Array();
trace("nextRockWave fired");
nextRockWave(null);
newShip(null);
}
// SCORE OBJECTS
// draw number of ships left
public function createShipIcons() {
shipIcons = new Array();
for(var i:uint=0;i<shipsLeft;i++) {
var newShip:ShipIcon = new ShipIcon();
newShip.x = 165+i*25; //165
newShip.y = 273; //273
scoreObjects.addChild(newShip);
shipIcons.push(newShip);
}
}
// draw number of shields left
public function createShieldIcons() {
shieldIcons = new Array();
for(var i:uint=0;i<shieldsLeft;i++) {
var newShield:ShieldIcon = new ShieldIcon();
newShield.x = 310-i*25; //530
newShield.y = 273; //15
scoreObjects.addChild(newShield);
shieldIcons.push(newShield);
}
}
// put the numerical score at the upper right
public function createScoreDisplay() {
updateScore();
}
// new score to show
public function updateScore() {
score.text = addCommaInNumber(gameScore);
}
// remove a ship icon
public function removeShipIcon() {
scoreObjects.removeChild(shipIcons.pop());
}
// remove a shield icon
public function removeShieldIcon() {
scoreObjects.removeChild(shieldIcons.pop());
}
// remove the rest of the ship icons
public function removeAllShipIcons() {
while (shipIcons.length > 0) {
removeShipIcon();
}
}
// remove the rest of the shield icons
public function removeAllShieldIcons() {
while (shieldIcons.length > 0) {
removeShieldIcon();
}
}
// SHIP CREATION AND MOVEMENT
// create a new ship
public function newShip(event:TimerEvent) {
// if ship exists, remove it
if (ship != null) {
gameObjects.removeChild(ship);
ship = null;
}
// no more ships
if (shipsLeft < 1) {
endGame();
return;
}
// create, position, and add new ship
ship = new Ship();
ship.gotoAndStop(1);
ship.x = 240; //275
ship.y = 160; //200
ship.rotation = -90;
ship.shield.visible = false;
gameObjects.addChild(ship);
// set up ship properties
shipMoveX = 0.0;
shipMoveY = 0.0;
gameMode = "play";
// set up shields
shieldsLeft = 3;
createShieldIcons();
// all lives but the first start with a free shield
if (shipsLeft != startingShips) {
startShield(true);
sndShield=new shield_sound();
sndShieldChannel=sndShield.play();
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
if (leftArrow) {
ship.rotation -= shipRotationSpeed*timeDiff;
} else if (rightArrow) {
ship.rotation += shipRotationSpeed*timeDiff;
} else if (upArrow) {
shipMoveX += Math.cos(Math.PI*ship.rotation/180)*thrustPower;
shipMoveY += Math.sin(Math.PI*ship.rotation/180)*thrustPower;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
// wrap around screen
if ((shipMoveX > 0) && (ship.x > 470)) {
ship.x -= 490;
}
if ((shipMoveX < 0) && (ship.x < -20)) {
ship.x += 500;
}
if ((shipMoveY > 0) && (ship.y > 320)) {
ship.y -= 340;
}
if ((shipMoveY < 0) && (ship.y < -20)) {
ship.y += 340;
}
}
// remove ship
public function shipHit() {
gameMode = "delay";
ship.gotoAndPlay("explode");
sndExplosion=new explosion_sound();
sndExplosionChannel=sndExplosion.play();
removeAllShieldIcons();
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,newShip);
delayTimer.start();
removeShipIcon();
shipsLeft--;
}
// turn on shield for 3 seconds
public function startShield(freeShield:Boolean) {
if (shieldsLeft < 1) return; // no shields left
if (shieldOn) return; // shield already on
// turn on shield and set timer to turn off
ship.shield.visible = true;
sndShield=new shield_sound();
sndShieldChannel=sndShield.play();
shieldTimer = new Timer(3000,1);
shieldTimer.addEventListener(TimerEvent.TIMER_COMPLETE,endShield);
shieldTimer.start();
// update shields remaining
if (!freeShield) {
removeShieldIcon();
shieldsLeft--;
}
shieldOn = true;
}
// turn off shield
public function endShield(event:TimerEvent) {
ship.shield.visible = false;
shieldOn = false;
}
// ROCKS
// create a single rock of a specific size
public function newRock(x,y:int, rockType:String) {
trace("newRock fired");
// create appropriate new class
var newRock:MovieClip;
var rockRadius:Number;
if (rockType == "Big") {
newRock = new Rock_Big();
rockRadius = 35;
} else if (rockType == "Medium") {
newRock = new Rock_Medium();
rockRadius = 20;
} else if (rockType == "Small") {
newRock = new Rock_Small();
rockRadius = 10;
}
// choose a random look
newRock.gotoAndStop(Math.ceil(Math.random()*3));
// set start position
newRock.x = x;
newRock.y = y;
// set random movement and rotation
var dx:Number = Math.random()*2.0-1.0;
var dy:Number = Math.random()*2.0-1.0;
var dr:Number = Math.random();
// add to stage and to rocks list
gameObjects.addChild(newRock);
setChildIndex(gameObjects,1); // I added this
rocks.push({rock:newRock, dx:dx, dy:dy, dr:dr, rockType:rockType, rockRadius: rockRadius});
}
// create four rocks
public function nextRockWave(event:TimerEvent) {
rocks = new Array();
newRock(30,30,"Big"); //100 100
newRock(30,290,"Big"); // 100 300
newRock(450,30,"Big"); // 450 100
newRock(450,290,"Big"); // 450 300
gameMode = "play";
}
// animate all rocks
public function moveRocks(timeDiff:uint) {
for(var i:int=rocks.length-1;i>=0;i--) {
// move the rocks
var rockSpeed:Number = rockSpeedStart + rockSpeedIncrease*gameLevel;
rocks[i].rock.x += rocks[i].dx*timeDiff*rockSpeed;
rocks[i].rock.y += rocks[i].dy*timeDiff*rockSpeed;
// rotate rocks
rocks[i].rock.rotation += rocks[i].dr*timeDiff*rockSpeed;
// wrap rocks
if ((rocks[i].dx > 0) && (rocks[i].rock.x > 470)) {
rocks[i].rock.x -= 490;
}
if ((rocks[i].dx < 0) && (rocks[i].rock.x < -20)) {
rocks[i].rock.x += 490;
}
if ((rocks[i].dy > 0) && (rocks[i].rock.y > 325)) {
rocks[i].rock.y -= 345;
}
if ((rocks[i].dy < 0) && (rocks[i].rock.y < -25)) {
rocks[i].rock.y += 345;
}
}
}
public function rockHit(rockNum:uint) {
// create two smaller rocks
sndBubble=new bubble_sound();
sndBubbleChannel=sndBubble.play();
if (rocks[rockNum].rockType == "Big") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Medium");
} else if (rocks[rockNum].rockType == "Medium") {
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
newRock(rocks[rockNum].rock.x,rocks[rockNum].rock.y,"Small");
}
// remove original rock
gameObjects.removeChild(rocks[rockNum].rock);
rocks.splice(rockNum,1);
}
// MISSILES
// create a new Missile
public function newMissile() {
// create
var newMissile:Missile = new Missile();
// set direction
newMissile.dx = Math.cos(Math.PI*ship.rotation/180);
newMissile.dy = Math.sin(Math.PI*ship.rotation/180);
// placement
newMissile.x = ship.x + newMissile.dx*shipRadius;
newMissile.y = ship.y + newMissile.dy*shipRadius;
// add to stage and array
gameObjects.addChild(newMissile);
missiles.push(newMissile);
}
// animate missiles
public function moveMissiles(timeDiff:uint) {
for(var i:int=missiles.length-1;i>=0;i--) {
// move
missiles[i].x += missiles[i].dx*missileSpeed*timeDiff;
missiles[i].y += missiles[i].dy*missileSpeed*timeDiff;
// moved off screen
if ((missiles[i].x < 0) || (missiles[i].x > 485) || (missiles[i].y < 0) || (missiles[i].y > 325)) {
gameObjects.removeChild(missiles[i]);
delete missiles[i];
missiles.splice(i,1);
}
}
}
// remove a missile
public function missileHit(missileNum:uint) {
gameObjects.removeChild(missiles[missileNum]);
missiles.splice(missileNum,1);
}
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
// get timer difference and animate
var timePassed:uint = getTimer() - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
// look for missiles colliding with rocks
public function checkCollisions() {
// loop through rocks
rockloop: for(var j:int=rocks.length-1;j>=0;j--) {
// loop through missiles
missileloop: for(var i:int=missiles.length-1;i>=0;i--) {
// collision detection
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(missiles[i].x,missiles[i].y))
< rocks[j].rockRadius) {
// remove rock and missile
rockHit(j);
missileHit(i);
// add score
gameScore += 10;
updateScore();
// break out of this loop and continue next one
continue rockloop;
}
}
// check for rock hitting ship
if (gameMode == "play") {
if (shieldOn == false) { // only if shield is off
if (Point.distance(new Point(rocks[j].rock.x,rocks[j].rock.y),
new Point(ship.x,ship.y))
< rocks[j].rockRadius+shipRadius) {
// remove ship and rock
shipHit();
rockHit(j);
}
}
}
}
// all out of rocks, change game mode and trigger more
if ((rocks.length == 0) && (gameMode == "play")) {
gameMode = "betweenlevels";
gameLevel++; // advance a level
levelTextBox.text = "Infection: " + gameLevel;
delayTimer = new Timer(2000,1);
delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextRockWave);
delayTimer.start();
}
}
public function endGame() {
// remove all objects and listeners
removeChild(gameObjects);
removeChild(scoreObjects);
removeChild(gameBackground);
gameObjects = null;
scoreObjects = null;
removeEventListener(Event.ENTER_FRAME,moveGameObjects);
gameMode = "gameOver";
gotoAndStop("gameover");
}
/***** ADD COMMAS TO NUMBERS *******/
function addCommaInNumber (number : Number) : String
{
var integer : String = "" ;
var fraction : String = "" ;
var string : String = number.toString();
var array : Array = string.split(".");
var regex : RegExp = /(\d+)(\d{3})/;
integer = array[0];
while( regex.test(integer) )
{
integer = integer.replace(regex,'$1' + ',' + '$2');
}
if (array[1])
{ fraction = integer.length > 0 ? '.' + array[1] : ''; }
return integer + fraction;
}
}
}
The part of code you thought applied to your problem is incorrect.
A timer can be started along with it's declaration as :
private var myTimer:Timer = new Timer(delay, repeat);
But since you are not initiating the timer at the time of declaration (as seen in you snippet)
// timers
private var delayTimer:Timer;
private var shieldTimer:Timer;
There must be some other function where it would be initiated. Move the action of initiating the timer to whichever place you want to start the timer. For eg : into startspacerocks() function
If that is not the problem, please post the relevant code that applies to your problem.
EDIT:
Well I think your answer lies in the moveGameObjects function.
Try modifying the function as follows:
// GAME INTERACTION AND CONTROL
public function moveGameObjects(event:Event) {
//Current Time
var currentTime:uint = getTimer();
//Initiate lastTime
if(lastTime == 0) lastTime = currentTime;
// get timer difference and animate
var timePassed:uint = currentTime - lastTime;
lastTime += timePassed;
moveRocks(timePassed);
if (gameMode != "delay") {
moveShip(timePassed);
}
moveMissiles(timePassed);
checkCollisions();
}
From the code you've posted, I can't answer your question safely, but you should check, when startSpaceRocks() is called the first time. This should be in the click handler of your start button.
Beside that, your question title does not reflect the problem. There is no problem with a timer at all, there is a problem, when the "timer" is started.