Simple Points & Lives Displaying Incorrectly - actionscript-3

so I'm working on this simple game, in which you dodge falling boulders. Every time a boulder doesn't hit you (reaches a y coordinate below) you get 30 pts. And when a boulder does hit you you lose a life. Unfortunately, it seems to glitch out seemingly unpredictable.
LINK TO TEST OUT THE GAME: http://fozgamez.com/a
(only the 1p mouse works)
I do not know how to fix the problem, since I cannot figure out how/ when the problem happens.
My code for the 2nd scene (the one with the rules):
import flash.events.MouseEvent;
stop();
var livesSelected:Number;
m1Select.addEventListener(MouseEvent.MOUSE_UP, m1Selected)
function m1Selected (e:MouseEvent)
{
livesSelected = 01;
gotoAndStop(3);
}
m3Select.addEventListener(MouseEvent.MOUSE_UP, m3Selected)
function m3Selected (e:MouseEvent)
{
livesSelected = 03;
gotoAndStop(3);
}
m5Select.addEventListener(MouseEvent.MOUSE_UP, m5Selected)
function m5Selected (e:MouseEvent)
{
livesSelected = 05;
gotoAndStop(3);
}
m9Select.addEventListener(MouseEvent.MOUSE_UP, m9Selected)
function m9Selected (e:MouseEvent)
{
livesSelected = 09;
gotoAndStop(3);
}
CODE FOR THE 3RD SCENE (where you actually play the game):
import flash.events.Event;
import flash.events.TouchEvent;
import flash.events.MouseEvent;
import flash.utils.Timer;
var points:int = 0;
var lifeTimer:Timer = new Timer(1000, 1)
var lives:Number = livesSelected;
livesText.text = lives.toString();
pointsText.text = points.toString();
lifeTimer.stop()
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event){
mChar.x = mouseX;
mChar.y = mouseY;
b1.y += 20;
b2.y += 40;
b3.y += 15;
b4.y += 25;
b5.y += 20;
bFast.y += 50;
if(mChar.y <= 20)
{
mChar.y = 20;
}
if(mChar.x >= 700)
{
mChar.x = 700;
}
if(mChar.y <= 0)
{
mChar.y = 700;
}
if(b1.y >= 730) {
b1.y = (Math.random() + .001) * -200;
b1.x = (Math.random() + .001) * 700;
points += 15;
}
if(b2.y >= 730) {
b2.y = (Math.random() + .001) * -200;
b2.x = (Math.random() + .001) * 700;
points += 30;
}
if(b3.y >= 730) {
b3.y = (Math.random() + .001) * -200;
b3.x = (Math.random() + .001) * 700;
points += 15;
}
if(b4.y >= 730) {
b4.y = (Math.random() + .001) * -200;
b4.x = (Math.random() + .001) * 700;
points += 15;
}
if(b5.y >= 730) {
b5.y = (Math.random() + .001) * -200;
b5.x = (Math.random() + .001) * 700;
points += 15;
}
if(bFast.y >= 730) {
bFast.y = (Math.random() + .001) * -200;
bFast.x = (Math.random() + .001) * 700;
points += 15;
}
if(!lifeTimer.running) {
livesText.text = lives.toString();
mInvin.x = -66;
mInvin.y = 560;
pointsText.text = points.toString();
if(mChar.hitTestObject(b1)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b2)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b3)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b4)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b5)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(bFast)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(lives <= 0)
{
gotoAndStop(7);
}
}
if(lifeTimer.running)
{
mInvin.x = mChar.x;
mInvin.y = mChar.y;
}
}
Thanks for reading: I know this is kind of a tough problem to figure out, so thanks for the help!

Your problem here, from what I can derive from your code, is your event listeners. I don't know what code you have on frame 7, but unless you remove the event listeners, they will keep on listening and running code, even though you have moved the playhead forward on the timeline (e.g. when calling gotoAndStop())

Related

Access of possibly undefined property alpha through a reference with static type Class

I'm not sure how to go about setting the transparency when the character's health goes down.
Error is on line 38
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Character extends MovieClip
{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
public function Character()
{
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
x = 300
y = 150
}
function takeDamage(d)
{
health -= d;
if(health <= 0)
{
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
Character.alpha = health/100;
}
function kill()
{
var blood = new Blood();
stage.addChild(blood);
blood.x = this.x;
blood.y = this.y;
removeEventListener("enterFrame",move);
this.visible = false;
Game.gameOver();
}
function move(e:Event)
{
shootLimiter += 5;
if(Key.isDown(Keyboard.RIGHT))
{
if(this.x <= 560)
{
this.x = this.x + velocity;
}
}
if(Key.isDown(Keyboard.LEFT))
{
if(this.x >= 40)
{
this.x = this.x - velocity;
}
}
if(Key.isDown(Keyboard.UP))
{
if(this.y > 20)
{
this.y = this.y - velocity;
}
}
if(Key.isDown(Keyboard.DOWN))
{
if(this.y < 280)
{
this.y = this.y + velocity;
}
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8)
{
shootLimiter = 0;
var b = new Needles();
stage.addChild(b);
b.x = this.x+65;
b.y = this.y+45;
}
}
}
}
Character has no static property called alpha. You are referring to the instance of the class and therefore it should be this.alpha = health/100; instead of Character.alpha = health/100;

AS3 How do I make these objects loop endlessly?

Here is my code so far, I am trying to create a top down car game and here is the code I have so far, I am currently trying to get the cars to loop but I am struggling to find a way to do it, please try and help me out with the code or point me in the right direction if you can please and thank you in advance
import flashx.textLayout.utils.CharacterUtil;
var result:Number = Math.random() * 100
var randomX:Number = Math.random() * stage.stageWidth
var background = new Background;
var char = new Char();
var car1 = new Car1();
var car2 = new Car2();
var car3 = new Car3();
var car4 = new Car4();
car1.x = Math.random()* stage.stageWidth;
car2.x = Math.random()* stage.stageWidth;
car3.x = Math.random()* stage.stageWidth;
car4.x = Math.random()* stage.stageWidth;
background.x = 200;
char.x = 700/2;
car1.y = -0;
car2.y = -150;
car3.y = -300;
car4.y = -450;
background.y = 200;
char.y = 450;
addChild(background);
addChild(char);
addChild(car1);
addChild(car2);
addChild(car3);
addChild(car4);
char.gotoAndStop("car");
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler(event:Event):void
{
car1.y +=12;
car2.y +=12;
car3.y +=12;
car4.y +=12;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_PressKeyToMove);
function fl_PressKeyToMove(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.RIGHT:
{
char.x += 15;
if (char.hitTestObject(barrier1))
{
char.x -=15 ;
}
break;
}
case Keyboard.LEFT:
{
char.x -= 15;
if (char.hitTestObject(barrier2))
{
char.x +=15 ;
}
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME, detectCollision);
function detectCollision(event:Event) {
if(char.hitTestObject(car1))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car2))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car3))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car4))
{
char.gotoAndStop("boom");
}
}
If you're trying to get cars to reposition to the top of the screen as #onekidney guessed, you could easily do so by using the % operator:
function fl_EnterFrameHandler(event:Event):void
{
car1.y = (car1.y + 12) % stage.stageHeight;
car2.y = (car2.y + 12) % stage.stageHeight;
car3.y = (car3.y + 12) % stage.stageHeight;
car4.y = (car4.y + 12) % stage.stageHeight;
}
You can read more about the modulo operator in the documentation

CS6 Error 1120: Access of undefined property p1RotateTimer

all.
I'm trying to use timers within my code for ship rotation, movement, and turret rotation in a battleship-themed project that I am working on. However, Error 1120 continues to show up, despite my efforts. Any advice?
Attached is my code. The problem occurs when I do utilize TurretArray and when I do addEventListener for the timers.
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.DisplayObject;
import flash.events.TimerEvent;
import flash.events.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.*;
import flash.text.*;
import flash.utils.*;
import fl.transitions.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.easing.None;
import flash.display.*;
import flash.ui.*;
[SWF(width = "600", height = "480")]
public class Main extends MovieClip
{
private var game:Game = new Game();
//Sets speeds to objects
private var bulletSpeed:int = 7;
private var playerSpeed:Number = 0.4;
private var playerRotateSpeed:Number = 0.1;
//Create an array to hold multiple sprites
private var mySpriteHolder = new Array();
private var BulletAngle = new Array();
private var BulletBounce = new Array();
//Create a counter to keep track of the sprites
private var lbCounter:int = 0;
//Maximum number of sprites (count starts a 1 not 0)
private var maxLB:int = 20;
//Variable for player 1
private var player1angle:Number = 270;
private var keyPressed1:int = 0;
private var keyPressed2:int = 0;
private var keyPressed3:int = 0;
private var keyPressed4:int = 0;
private var p1Score:int = 0;
private var reloaded:int = 0;
private var k:int = 0;
private var reloadTime:int = 10;
private var TurretArray:Array = new Array();
//public function loadTurrets(){
//TurretArray = new Array();
TurretArray[0] = mvi_PTurret1; //Problem occurs in these 3 lines
TurretArray[1] = mvi_PTurret2;
TurretArray[2] = mvi_PTurret3;
//}
private var Turret1SpinDirection:int = 2;
private var Turret2SpinDirection:int = 2;
private var PTurret1angle:Number = 270;
private var PTurret2angle:Number = 270;
//create a new Timer
private var p1RotateTimer:Timer = new Timer(10);
private var p1MoveTimer:Timer = new Timer(10);
private var PTurretRotateTimer:Timer = new Timer(10);
//public function loadTimers(){
//add a listener to the timer
p1RotateTimer.addEventListener("timer",p1Rotate); //Problem here
p1MoveTimer.addEventListener("timer",p1Move);
PTurretRotateTimer.addEventListener("timer",PTurretRotate);
//}
//Create a listener for the keypress
//this.addEventListener(KeyboardEvent.KEY_DOWN,PMove);
// this.addEventListener(KeyboardEvent.KEY_UP,PStop);
// this.addEventListener(MouseEvent.MOUSE_MOVE,mouseCoordinate);
public function p1Rotate(eventArgs:TimerEvent):void{
var i:int;
if(keyPressed1 == 68){
mvi_PBattleship.rotation += playerRotateSpeed;
player1angle += playerRotateSpeed;
if(player1angle == 360){
player1angle = 0;
}
/*for(i = 0; i < 3; i++){
TurretArray[i].rotation += playerRotateSpeed;
TurretArray[i].rotation = Math.round(TurretArray[i].rotation);
}*/
//txt_PlayerAngle.text = player1angle.toString();
}
if(keyPressed2 == 65){
mvi_PBattleship.rotation -= playerRotateSpeed;
player1angle -= playerRotateSpeed;
if(player1angle == 0){
player1angle = 360;
}
/*for(i = 0; i < 3; i++){
TurretArray[i].rotation -= playerRotateSpeed;
TurretArray[i].rotation = Math.round(TurretArray[i].rotation);
}*/
//txt_PlayerAngle.text = player1angle.toString();
}
//Keeps Turret 1 with the ship
mvi_PTurret1.x = Math.cos(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.x;
mvi_PTurret1.y = Math.sin(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.y;
//Keeps Turret 2 with the ship
mvi_PTurret2.x = Math.cos(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.x;
mvi_PTurret2.y = Math.sin(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.y;
//Keeps Turret 3 with the ship
mvi_PTurret3.x = Math.cos(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.x;
mvi_PTurret3.y = Math.sin(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.y;
}
public function p1Move(eventArgs:TimerEvent):void{
/*if(p1Score > 0){
p1Score -= pointsLost;
}*/
//This moves the player forward or backwards in the correct direction
if(keyPressed3 == 87){
x -= Math.cos(player1angle* (Math.PI/180)) * playerSpeed;
y -= Math.sin(player1angle* (Math.PI/180)) * playerSpeed;
}
if(keyPressed4 == 83){
x += Math.cos(player1angle* (Math.PI/180)) * playerSpeed;
y += Math.sin(player1angle* (Math.PI/180)) * playerSpeed;
}
//This keeps the player in the center of the screen
mvi_PBattleship.x =-x + 400;
mvi_PBattleship.y =-y + 300;
//txt_PBattleshipx.text = x.toString();
//txt_PBattleshipy.text = y.toString();
//Keeps Turret 1 with the ship
mvi_PTurret1.x = Math.cos(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.x;
mvi_PTurret1.y = Math.sin(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.y;
//Keeps Turret 2 with the ship
mvi_PTurret2.x = Math.cos(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.x;
mvi_PTurret2.y = Math.sin(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.y;
//Keeps Turret 3 with the ship
mvi_PTurret3.x = Math.cos(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.x;
mvi_PTurret3.y = Math.sin(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.y;
}
public function PMove(Evt:KeyboardEvent):void{
//trace(Evt.keyCode);
if(Evt.keyCode==68){
keyPressed1 = 68;
p1RotateTimer.start();
}
if(Evt.keyCode==65){
keyPressed2 = 65;
p1RotateTimer.start();
}
if(Evt.keyCode==87){
keyPressed3 = 87;
p1MoveTimer.start();
}
if(Evt.keyCode==83){
keyPressed4 = 83;
p1MoveTimer.start();
}
}
public function PStop(Evt:KeyboardEvent):void{
if(Evt.keyCode==87){
keyPressed3 = 0;
p1MoveTimer.stop();
}
else if(Evt.keyCode==83){
keyPressed4 = 0;
p1MoveTimer.stop();
}
else if(Evt.keyCode==68){
keyPressed1 = 0;
p1RotateTimer.stop();
}
else if(Evt.keyCode==65){
keyPressed2 = 0;
p1RotateTimer.stop();
}
}
public function PTurretRotate(Evt:Event){
var Mouse1x:Number;
var Mouse1y:Number;
var Mouse1Angle:Number;
Mouse1x = mvi_PTurret1.x - mouseX;
Mouse1y = mvi_PTurret1.y - mouseY;
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180);
if(Turret1SpinDirection == 0 && Mouse1Angle < 90 && PTurret1angle > 270){
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180)+ 360;
}
else if(Turret1SpinDirection == 1 && Mouse1Angle > 270 && PTurret1angle < 90){
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180)- 360;
}
if(PTurret1angle > 360){
PTurret1angle = 1;
}
if(PTurret1angle < 0){
PTurret1angle = 359;
}
if(PTurret1angle < Math.round(player1angle) - 210 || PTurret1angle > Math.round(player1angle) - 150){
if(Mouse1Angle > PTurret1angle){
mvi_PTurret1.rotation += 1;
PTurret1angle += 1;
Turret1SpinDirection = 0;
}
else if(Mouse1Angle < PTurret1angle){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
Turret1SpinDirection = 1;
}
}
else{
if(PTurret1angle == Math.round(player1angle) - 210){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
}
else if(Math.round(player1angle) - 210 < 0){
if(PTurret1angle + 90 == Math.round(player1angle) - 210 + 90){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
}
}
if(PTurret1angle == Math.round(player1angle) - 150){
mvi_PTurret1.rotation += 1;
PTurret1angle += 1;
}
}
var Mouse2x:Number;
var Mouse2y:Number;
var Mouse2Angle:Number;
Mouse2x = mvi_PTurret2.x - mouseX;
Mouse2y = mvi_PTurret2.y - mouseY;
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180);
if(Turret2SpinDirection == 0 && Mouse2Angle < 90 && PTurret2angle > 270){
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180)+ 360;
}
else if(Turret2SpinDirection == 1 && Mouse2Angle > 270 && PTurret2angle < 90){
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180)- 360;
}
if(PTurret2angle > 360){
PTurret2angle = 1;
}
if(PTurret2angle < 0){
PTurret2angle = 359;
}
if(Mouse2Angle > PTurret2angle){
mvi_PTurret2.rotation += 1;
PTurret2angle += 1;
Turret2SpinDirection = 0;
}
else if(Mouse2Angle < PTurret2angle){
mvi_PTurret2.rotation -= 1;
PTurret2angle -= 1;
Turret2SpinDirection = 1;
}
//txt_Turret1Angle.text = Mouse1Angle.toString();
//txt_PTurret.text = PTurret1angle.toString();
}
public function mouseCoordinate(Evt:Event){
//txt_X.text = mouseX.toString();
//txt_Y.text = mouseY.toString();
PTurretRotateTimer.start();
}
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
stage.frameRate = 30;
addChild(game);
}
private function mouseMove(e :MouseEvent) :void {
Game.mouse.x = e.stageX;
Game.mouse.y = e.stageY;
}
private function enterFrame(e :Event) :void {
game.update();
}
}
}
Thank you very much.

Actionscript 3 Score count on hitTestObject

I've been working on this simple car game in Flash CS5. The car has to avoid the cars coming vertically and pick up coins. I have three types of coins which add 1, 2 and 3 score points on being picked up. My problem is that when I hit the coin with the car it goes through the car and gives much more points. I also have problem with removing it from the stage... Here the code so far:
var spex:Number = 0;
var spey:Number = 4;
var score:uint;
var cars:Array = new Array ;
var db:Number = 2;
var db_coins:Number = 1;
var i:Number = 0;
for (i=0; i<=db; i++)
{
var traffic_mc:MovieClip = new traffic ;
cars.push(addChild(traffic_mc));
cars[i].x = -500 * Math.random();
cars[i].y = Math.random() * 400;
trace(cars[i].y);
}
for (i=0; i<=db_coins; i++)
{
var coin_y:MovieClip = new coin_yellow ;
coin_y.x = -500 * Math.random();
coin_y.y = Math.random() * 400;
addChild(coin_y);
var coin_r:MovieClip = new coin_red ;
coin_y.x = -500 * Math.random();
coin_y.y = Math.random() * 400;
addChild(coin_r);
var coin_b:MovieClip = new coin_blue ;
coin_b.x = -500 * Math.random();
coin_b.y = Math.random() * 400;
addChild(coin_b);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(k:KeyboardEvent):void
{
if (k.keyCode == 37)
{
spex -= 4;
}
if (k.keyCode == 39)
{
spex += 4;
}
}
stage.addEventListener(Event.ENTER_FRAME, go);
function go(e:Event):void
{
this.auto.x += spex;
if (this.auto.x < 25)
{
this.auto.x = 25;
spex = 0;
}
if (this.auto.x > 286)
{
this.auto.x = 286;
spex = 0;
}
for (i=0; i<=db; i++)
{
if (cars[i].hitTestObject(this.auto))
{
trace("GAME OVER");
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keydown);
stage.removeEventListener(Event.ENTER_FRAME, go);
stage.addEventListener(KeyboardEvent.KEY_DOWN, retry);
}
cars[i].y += spey;
if (cars[i].y > 600)
{
cars[i].y = -50;
cars[i].x = Math.random() * 251;
}
}
for (i=0; i<=db_coins; i++)
{
if (coin_y.hitTestObject(this.auto))
{
score += 1;
updateScore();
}
coin_y.y += spey-2;
if (coin_y.y > 600)
{
coin_y.y = -50;
coin_y.x = Math.random() * 251;
}
if (coin_r.hitTestObject(this.auto))
{
score += 2;
updateScore();
}
coin_r.y += spey-2;
if (coin_r.y > 600)
{
coin_r.y = -50;
coin_r.x = Math.random() * 251;
}
if (coin_b.hitTestObject(this.auto))
{
score += 3;
updateScore();
}
coin_b.y += spey-2;
if (coin_b.y > 600)
{
coin_b.y = -50;
coin_b.x = Math.random() * 251;
}
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, retry);
function retry(k:KeyboardEvent):void
{
if (k.keyCode == 32)
{
stage.addEventListener(Event.ENTER_FRAME, go);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
for (i=0; i<=db; i++)
{
cars[i].y = -300 * Math.random();
cars[i].x = Math.random() * 251;
}
for (i=0; i<=db_coins; i++)
{
coin_y.y = -300 * Math.random();
coin_y.x = Math.random() * 251;
coin_r.y = -300 * Math.random();
coin_r.x = Math.random() * 251;
coin_b.y = -300 * Math.random();
coin_b.x = Math.random() * 251;
}
spex = 0;
spey = 4;
score = 0;
scorecounter.text = "Score: " + score.toString();
}
}
//Scorecount
function init():void
{
score = 0;
scorecounter.text = "Score: " + score.toString();
}
function updateScore():void
{
scorecounter.text = "Score: " + score.toString();
}
init();
i think you should create a variable like hited:Boolean and check first hit. Coin issue occurs cause coin isn't hitting for one time, it is hitting for a while cause every frame you move it and with movement it hits again. So you have to check it and make a proper "if-else" condition.
There is a better solution than the one you decided to use. spex is the variable that you are using to scroll the game. When you run your hitTestObject on the car simply put spex = 0; This will stop the game dead.
I agree with mitim to use removeChild() for the coins instead of just piling them up off stage.

Game Over function is not working Starling

I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code.
package screens
{
import flash.geom.Rectangle;
import flash.utils.getTimer;
import events.NavigationEvent;
import objects.GameBackground;
import objects.Hero;
import objects.Item;
import objects.Obstacle;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.text.TextField;
import starling.utils.deg2rad;
public class InGame extends Sprite
{
private var screenInGame:InGame;
private var screenWelcome:Welcome;
private var startButton:Button;
private var playAgain:Button;
private var bg:GameBackground;
private var hero:Hero;
private var timePrevious:Number;
private var timeCurrent:Number;
private var elapsed:Number;
private var gameState:String;
private var playerSpeed:Number = 0;
private var hitObstacle:Number = 0;
private const MIN_SPEED:Number = 650;
private var scoreDistance:int;
private var obstacleGapCount:int;
private var gameArea:Rectangle;
private var touch:Touch;
private var touchX:Number;
private var touchY:Number;
private var obstaclesToAnimate:Vector.<Obstacle>;
private var itemsToAnimate:Vector.<Item>;
private var scoreText:TextField;
private var remainingLives:TextField;
private var gameOverText:TextField;
private var iconSmall:Image;
static private var lives:Number = 2;
public function InGame()
{
super();
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
drawGame();
scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true);
remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true);
iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1"));
iconSmall.x = 360;
iconSmall.y = 40;
this.addChild(iconSmall);
this.addChild(scoreText);
this.addChild(remainingLives);
}
private function drawGame():void {
bg = new GameBackground();
this.addChild(bg);
hero = new Hero();
hero.x = stage.stageHeight / 2;
hero.y = stage.stageWidth / 2;
this.addChild(hero);
startButton = new Button(Assets.getAtlas().getTexture("startButton"));
startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5;
this.addChild(startButton);
gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250);
}
public function disposeTemporarily():void {
this.visible = false;
}
public function initialize():void {
this.visible = true;
this.addEventListener(Event.ENTER_FRAME, checkElapsed);
hero.x = -stage.stageWidth;
hero.y = stage.stageHeight * 0.5;
gameState ="idle";
playerSpeed = 0;
hitObstacle = 0;
bg.speed = 0;
scoreDistance = 0;
obstacleGapCount = 0;
obstaclesToAnimate = new Vector.<Obstacle>();
itemsToAnimate = new Vector.<Item>();
startButton.addEventListener(Event.TRIGGERED, onStartButtonClick);
//var mainStage:InGame =InGame.current.nativeStage;
//mainStage.dispatchEvent(new Event(Event.COMPLETE));
//playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onStartButtonClick(event:Event):void {
startButton.visible = false;
startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick);
launchHero();
}
private function launchHero():void {
this.addEventListener(TouchEvent.TOUCH, onTouch);
this.addEventListener(Event.ENTER_FRAME, onGameTick);
}
private function onTouch(event:TouchEvent):void {
touch = event.getTouch(stage);
touchX = touch.globalX;
touchY = touch.globalY;
}
private function onGameTick(event:Event):void {
switch(gameState) {
case "idle":
if(hero.x < stage.stageWidth * 0.5 * 0.5) {
hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05;
hero.y = stage.stageHeight * 0.5;
playerSpeed += (MIN_SPEED - playerSpeed) * 0.05;
bg.speed = playerSpeed * elapsed;
} else {
gameState = "flying";
}
break;
case "flying":
if(hitObstacle <= 0) {
hero.y -= (hero.y - touchY) * 0.1;
if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) {
hero.rotation = deg2rad(-(hero.y - touchY) * 0.2);
}
if(hero.y > gameArea.bottom - hero.height * 0.5) {
hero.y = gameArea.bottom - hero.height * 0.5;
hero.rotation = deg2rad(0);
}
if(hero.y < gameArea.top + hero.height * 0.5) {
hero.y = gameArea.top + hero.height * 0.5;
hero.rotation = deg2rad(0);
}
} else {
hitObstacle--
cameraShake();
}
playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01;
bg.speed = playerSpeed * elapsed;
scoreDistance += (playerSpeed * elapsed) * 0.1;
scoreText.text = "Score: " + scoreDistance;
initObstacle();
animateObstacles();
createEggItems();
animateItems();
remainingLives.text = "Lives: "+lives + " X ";
if(lives == 0) {
gameState = "over";
}
break;
case "over":
gameOver();
break;
}
}
private function gameOver():void {
gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true);
scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true);
this.addChild(scoreText);
this.addChild(gameOverText);
playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain"));
playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75;
this.addChild(playAgain);
playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onRetry(event:Event):void {
playAgain.visible = false;
gameOverText.visible = false;
scoreText.visible = false;
var btnClicked:Button = event.target as Button;
if((btnClicked as Button) == playAgain) {
this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true));
}
disposeTemporarily();
}
private function animateItems():void {
var itemToTrack:Item;
for(var i:uint = 0; i < itemsToAnimate.length; i++) {
itemToTrack = itemsToAnimate[i];
itemToTrack.x -= playerSpeed * elapsed;
if(itemToTrack.bounds.intersects(hero.bounds)) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
if(itemToTrack.x < -50) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
}
}
private function createEggItems():void {
if(Math.random() > 0.95){
var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10));
itemToTrack.x = stage.stageWidth + 50;
itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top;
this.addChild(itemToTrack);
itemsToAnimate.push(itemToTrack);
}
}
private function cameraShake():void {
if(hitObstacle > 0) {
this.x = Math.random() * hitObstacle;
this.y = Math.random() * hitObstacle;
} else if(x != 0) {
this.x = 0;
this.y = 0;
lives--;
}
}
private function initObstacle():void {
if(obstacleGapCount < 1200) {
obstacleGapCount += playerSpeed * elapsed;
} else if(obstacleGapCount !=0) {
obstacleGapCount = 0;
createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000);
}
}
private function animateObstacles():void {
var obstacleToTrack:Obstacle;
for(var i:uint = 0; i<obstaclesToAnimate.length; i++) {
obstacleToTrack = obstaclesToAnimate[i];
if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) {
obstacleToTrack.alreadyHit = true;
obstacleToTrack.rotation = deg2rad(70);
hitObstacle = 30;
playerSpeed *= 0.5;
}
if(obstacleToTrack.distance > 0) {
obstacleToTrack.distance -= playerSpeed * elapsed;
} else {
if(obstacleToTrack.watchOut) {
obstacleToTrack.watchOut = false;
}
obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed;
}
if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") {
obstaclesToAnimate.splice(i, 1);
this.removeChild(obstacleToTrack);
}
}
}
private function checkElapsed(event:Event):void {
timePrevious = timeCurrent;
timeCurrent = getTimer();
elapsed = (timeCurrent - timePrevious) * 0.001;
}
private function createObstacle(type:Number, distance:Number):void{
var obstacle:Obstacle = new Obstacle(type, distance, true, 300);
obstacle.x = stage.stageWidth;
this.addChild(obstacle);
if(type >= 4) {
if(Math.random() > 0.5) {
obstacle.y = gameArea.top;
obstacle.position = "top"
} else {
obstacle.y = gameArea.bottom - obstacle.height;
obstacle.position = "bottom";
}
} else {
obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top;
obstacle.position = "middle";
}
obstaclesToAnimate.push(obstacle);
}
}
}
You're not calling initialize() anywhere, which is where the gameState is initially set to "idle" it seems... what does this code do currently when you run it?
The goal here is to get the onGameTick(event) function running every frame, which is going to switch between idle/flying/over game states.