Game Over function is not working Starling - actionscript-3

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.

Related

State Machine Cant get to work

Learning to code so this might sound noobish...
Using Action Script
I am trying to make my Agents react to my segments so they run away.
So I need to connect part of my Main code to my Agent code
Here is my code :
Main.as
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.display.Stage;
public class Main extends Sprite
{
private var score:Score;
private var count:int;
private var bleh: int = 0;
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 20;
private var player:Point = new Point (200, 200)
private var friend:Agent = new Agent;
private var snakeHead:SnakeHead;
private var snakeTail:SnakeTail;
private var background: Sprite;
private var border: Bushes;
private var xVel: Number;
private var yVel: Number;
public function Main():void
{
xVel = 0;
yVel = 0;
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
snakeHead = new SnakeHead();
snakeTail = new SnakeTail();
score = new Score();
border = new Bushes;
score.x = 11;
score.y = 14;
addChild(score);
stage.addChild(border);
count = 0;
addChildAt(snakeHead,0);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (10, 20);
addChildAt(segment,0);
addChildAt(snakeTail,0);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
background = new LevelOne(); //creates the background
addChildAt(background,0);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 3; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = 400;
a.y = 300;
a.name = "Name"+x;
trace (x);
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(evt:Event):void
{
for (var i:int = 0; i < Agents.length; i++)
{
Agents[i].update();
if (snakeHead.hitTestObject(Agents[i]))
{
//trace (Agents[i].name);
removeAgent(Agents[i]);
Agents.splice(i,1);
count ++;
score.lowercasetext.text = count.toString();
trace("count: " + count);
}
}
}
private function onEnterFrame(evt:Event):void
{
player.x += xVel;
player.y += yVel;
drag(snakeHead, player.x, player.y);
drag(segments[0], snakeHead.x, snakeHead.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
var PlayerHalfWidth: Number = segments[i].width / 2;
var PlayerHalfHeight: Number = segments[i].height / 2;
if (segments[i].x + PlayerHalfWidth > stage.stageWidth) {
segments[i].x = stage.stageWidth - PlayerHalfWidth;
} else if (segments[i].x - PlayerHalfWidth < 0) {
segments[i].x = 0 + PlayerHalfWidth;
}
if (segments[i].y + PlayerHalfHeight > stage.stageHeight) {
segments[i].y = stage.stageHeight - PlayerHalfHeight;
}else if (segments[i].y - PlayerHalfHeight < 0) {
segments[i].y = 0 + PlayerHalfHeight;
}
var playerHalfWidth: Number = segments[i - 1].width / 2;
var playerHalfHeight: Number = segments[i - 1].height / 2;
if (segments[i - 1].x + playerHalfWidth > stage.stageWidth) {
segments[i - 1].x = stage.stageWidth - playerHalfWidth;
} else if (segments[i - 1].x - playerHalfWidth < 0) {
segments[i - 1].x = 0 + playerHalfWidth;
}
if (segments[i - 1].y + playerHalfHeight > stage.stageHeight) {
segments[i - 1].y = stage.stageHeight - playerHalfHeight;
}else if (segments[i - 1].y - playerHalfHeight < 0) {
segments[i - 1].y = 0 + playerHalfHeight;
}
}
drag(snakeTail, segments[19].x, segments[19].y);
var HeadHalfWidth: Number = snakeHead.width / 2;
var HeadHalfHeight: Number = snakeHead.height / 2;
if (snakeHead.x + HeadHalfWidth > stage.stageWidth) {
snakeHead.x = stage.stageWidth - HeadHalfWidth;
} else if (snakeHead.x - HeadHalfWidth < 0) {
snakeHead.x = 0 + HeadHalfWidth;
}
if (snakeHead.y + HeadHalfHeight > stage.stageHeight) {
snakeHead.y = stage.stageHeight - HeadHalfHeight;
}else if (snakeHead.y - HeadHalfHeight < 0) {
snakeHead.y = 0 + HeadHalfHeight;
}
//drag(segments[19], snakeTail.x, snakeTail.y);
/*for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
if(segments[0].hitTestObject(a))
{
trace("True");
trace(bleh + " " + "F*CKING HELL!");
trace(a.name);
stage.removeChild(Agents[1]);
}
}*/
}
private function removeAgent(a:Agent):void
{
a.parent.removeChild(a);
trace("Collision Detected!");
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = -5;
}
if (evt.keyCode == 83)
{
player;
yVel = 5;
}
if (evt.keyCode == 68)
{
player;
xVel = 5;
}
if (evt.keyCode == 65)
{
player;
xVel = -5;
}
//trace (player.x + " " + player.y);
trace (xVel + " " + yVel);
}
private function keyUp (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = 0;
}
else if (evt.keyCode == 83)
{
player;
yVel = 0;
}
else if (evt.keyCode == 68)
{
player;
xVel = 0;
}
else if (evt.keyCode == 65)
{
player;
xVel = 0;
}
}
private function drag(segment:MovieClip, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Agent.as
package agent
{
import agent.states.ChaseState;
import agent.states.ConfusionState;
import agent.states.FleeState;
import agent.states.IAgentState;
import agent.states.IdleState;
import agent.states.WanderState;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.*;
import Segment;
import Main;
public class Agent extends MovieClip
{
private var mouses:mouse;
public static const IDLE:IAgentState = new IdleState(); //Define possible states as static constants
public static const WANDER:IAgentState = new WanderState();
public static const CHASE:IAgentState = new ChaseState();
public static const FLEE:IAgentState = new FleeState();
public static const CONFUSED:IAgentState = new ConfusionState();
public var snake:Segment;
private const RAD_DEG:Number = 180 / Math.PI;
private var _previousState:IAgentState; //The previous executing state
private var _currentState:IAgentState; //The currently executing state
private var _pointer:Shape;
private var _tf:TextField;
public var velocity:Point = new Point();
public var speed:Number = 0;
public var fleeRadius:Number = 100; //If the mouse is "seen" within this radius, we want to flee
public var chaseRadius:Number = 50; //If the mouse is "seen" within this radius, we want to chase
public var numCycles:int = 0; //Number of updates that have executed for the current state. Timing utility.
public function Agent()
{
//Boring stuff here
_tf = new TextField();
_tf.defaultTextFormat = new TextFormat("_sans", 10);
_tf.autoSize = TextFieldAutoSize.LEFT;
_pointer = new Shape();
mouses = new mouse();
snake = new Segment(1, 1);
/*g.beginFill(0);
g.drawCircle(0, 0, 5);
g.endFill();
g.moveTo(0, -5);
g.beginFill(0);
g.lineTo(10, 0);
g.lineTo(0, 5);
g.endFill();*/
addChild(mouses);
addChild(_tf);
_currentState = IDLE; //Set the initial state
}
/**
* Outputs a line of text above the agent's head
* #param str
*/
public function say(str:String):void {
_tf.text = str;
_tf.y = -_tf.height - 2;
}
/**
* Trig utility methods
*/
public function get canSeeMouse():Boolean {
var dot:Number = snake.x * velocity.x + snake.y * velocity.y;
return dot > 0;
}
public function get distanceToMouse():Number {
var dx:Number = x - snake.x;
var dy:Number = y - snake.y;
return Math.sqrt(dx * dx + dy * dy);
}
public function randomDirection():void {
var a:Number = Math.random() * 6.28;
velocity.x = Math.cos(a);
velocity.y = Math.sin(a);
}
public function faceMouse(multiplier:Number = 1):void {
var dx:Number = snake.x - x;
var dy:Number = snake.y - y;
var rad:Number = Math.atan2(dy, dx);
velocity.x = multiplier*Math.cos(rad);
velocity.y = multiplier*Math.sin(rad);
}
/**
* Update the current state, then update the graphics
*/
public function update():void {
if (!_currentState) return; //If there's no behavior, we do nothing
numCycles++;
_currentState.update(this);
x += velocity.x*speed;
y += velocity.y*speed;
if (x + velocity.x > stage.stageWidth || x + velocity.x < 0) {
x = Math.max(0, Math.min(stage.stageWidth, x));
velocity.x *= -1;
}
if (y + velocity.y > stage.stageHeight || y + velocity.y < 0) {
y = Math.max(0, Math.min(stage.stageHeight, y));
velocity.y *= -1;
}
mouses.rotation = RAD_DEG * Math.atan2(velocity.y, velocity.x);
}
public function setState(newState:IAgentState):void {
if (_currentState == newState) return;
if (_currentState) {
_currentState.exit(this);
}
_previousState = _currentState;
_currentState = newState;
_currentState.enter(this);
numCycles = 0;
}
public function get previousState():IAgentState { return _previousState; }
public function get currentState():IAgentState { return _currentState; }
}
}

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;

How to implement enemy behaviour based on type?

I am building a game which create three types of enemy.Amount them only type 3 can fire others cannt.This is my enemy class
package
{
import flash.display.MovieClip;
import flash.utils.getTimer;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class Enemy extends MovieClip
{
private var lastTime:int;
var hitCounter:Number = 1;
public var eType:Number = 0;
private var startYpos:Number = 0;
var nextFire:Timer;
var enemyType:Number;
public var bullets:Array = new Array ;
var speedY:Number = 50;
var enemySpeed:Number = 50;
var firstPos:Number = 0;
var fireCounter:Number = 0;
var firePause:Number = 10;
public function Enemy(xPos,yPos:Number,t:Number)
{
// constructor code
this.x = xPos;
firstPos = this.y = yPos;
this.enemyType = t;
lastTime = getTimer();
this.gotoAndStop(t);
addEventListener(Event.ENTER_FRAME,moveEnemy);
}
public function moveEnemy(event:Event)
{
// get time passed
var timePassed:int = getTimer() - lastTime;
lastTime += timePassed;
// move bullet
if (this.y + this.height / 2 > firstPos + 100 && speedY > 0)
{
speedY *= -1;
}
if (this.y - this.height / 2 < firstPos && speedY < 0)
{
speedY *= -1;
}
this.x -= enemySpeed * timePassed / 1000;
this.y += speedY * timePassed / 1000;
// bullet past top of screen
if (this.x - this.width / 2 < 0)
{
deleteEnemy();
}
if (this.enemyType == 3)
{
canFire();
}
}
public function canFire()
{
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
public function deleteEnemy()
{
if (this.currentFrame == 2)
{
this.gotoAndStop(4);
}
else
{
//trace(MovieClip(parent).enemyKilled[this.enemyType-1]);
MovieClip(parent).enemyKilled[this.enemyType - 1]++;
MovieClip(parent).removeEnemy(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveEnemy);
}
}
}
}
Now once a enemy type 3 start firing then every enemy start firing.i want just only enemy type 3 can fire not other enemy.How i do it?
Thanks in advance
Addition :
public function createEnemyBullet()
{
var bullet:Bullet = new Bullet(enemy.x - 10,enemy.y,500,-1);
bullets.push(bullet);
addChild(bullet);
//setEnemyBullet();
}
Then why don't you try something like this. `
public function canFire()
{
if(enemyType == 3){
return;
}
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
`

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.

procedural generating terrain

Iv managed to get a somewhat working procedural generated terrain. But.. for some reason my tiles get placed 1 square to the left on the screen on the second row on, and then makes 2 extra tiles at the end :D
Im sure it has something to do with
tile.y += TILE_SIZE *(Math.floor(tilesInWorld.length/ROW_LENGTH));
tile.x = TILE_SIZE * (tilesInWorld.length-(ROW_LENGTH*Math.floor(tilesInWorld.length/ROW_LENGTH)));
but im not sure...
heres the code for the generated terrain tho
package
{
import flash.display.*;
import flash.events.Event;
public class World
{
protected var tilesInWorld:Vector.<MovieClip> = new Vector.<MovieClip>();
public var worldTiles:Sprite;
protected var tile:MovieClip;
protected var TILE_SIZE = 25;
protected var MAP_WIDTH = 800;
protected var MAP_HEIGHT = 600;
protected var ROW_LENGTH = (MAP_WIDTH/TILE_SIZE)+1;
protected var COL_LENGTH = (MAP_HEIGHT/TILE_SIZE);
protected var MAX_WATER = 100;
protected var waterTiles;
protected var nextTile:String;
protected var maxTiles = ROW_LENGTH * COL_LENGTH;
protected var waterChain:int;
protected var waterBuffer:int;
public function World(parentMC:MovieClip)
{
waterBuffer = Math.random()*(maxTiles-MAX_WATER);
waterTiles = 0;
waterChain = 5;
nextTile = "";
parentMC.addEventListener(Event.ENTER_FRAME, update);
worldTiles = new Sprite();
parentMC.addChild(worldTiles);
}
protected function generateTile()
{
if (tilesInWorld.length > 0)
{
if (waterTiles >= MAX_WATER)
{
tile = new Grass();
nextTile = "grass";
trace(waterTiles);
}
else
{
if(tilesInWorld.length + 1 < waterBuffer){
nextTile = "grass";
}
for (var i:int = 0; i < tilesInWorld.length; i++)
{
if (tilesInWorld[i].x == (tilesInWorld[tilesInWorld.length-1].x + TILE_SIZE) && tilesInWorld[i].y == (tilesInWorld[tilesInWorld.length-1].y-TILE_SIZE) && tilesInWorld[i].type == "water")
{
nextTile = "water";
}
}
if (nextTile == "grass")
{
tile = new Grass();
nextTile = "";
waterChain = 0;
}
else if (nextTile == "water")
{
waterTiles += 1;
waterChain += 1;
tile = new Water();
if (waterChain > 5)
{
nextTile = "";
}
else
{
nextTile = "water";
}
}
else
{
if (Math.random() * 1 >= 0.25)
{
waterChain = 0;
tile = new Grass();
nextTile = "grass";
}
else
{
waterTiles += 1;
waterChain += 1;
tile = new Water();
nextTile = "water";
}
}
}
}
else
{
if (Math.random() * 1 >= 0.5)
{
waterChain = 0;
nextTile = "grass";
tile = new Grass();
}
else
{
waterTiles += 1;
waterChain += 1;
nextTile = "water";
tile = new Water();
}
}
this is where the actual coding for placing the X and Y potion of the tiles is located, in other words, this is the place where i believe the error is at
tilesInWorld.push(tile);
tile.width = TILE_SIZE;
tile.height = TILE_SIZE;
worldTiles.x = 0-(tile.width/2);
worldTiles.y = 0+(tile.height/2);
tile.x = TILE_SIZE * tilesInWorld.length;
if (tile.x >= MAP_WIDTH)
{
tile.y += TILE_SIZE * (Math.floor(tilesInWorld.length/ROW_LENGTH));
tile.x = TILE_SIZE * (tilesInWorld.length-(ROW_LENGTH*Math.floor(tilesInWorld.length/ROW_LENGTH)));
}
worldTiles.addChild(tile);
}
protected function allowTile():Boolean
{
//if()
if (tilesInWorld.length > maxTiles)
{
return false;
}
return true;
}
protected function update(e:Event)
{
if (allowTile())
{
generateTile();
}
}
}
}
heres a link to the game for you can actually see what it is doing
http://www.fastswf.com/p13LrYA
just realized you cant see what its doing because its off the screen lolol :D
Also, if anyone could help make a better way of making random lakes in the terrain?
But thanks ahead of time for the help!
Change
protected var ROW_LENGTH = (MAP_WIDTH/TILE_SIZE); //remove the +1
Remove
if (tile.x >= MAP_WIDTH)
and you can calculate a tiles x,y from its index (which you can get using tilesInWorld.length before they are added) using:
tile.x = TILE_SIZE * (tilesInWorld.length % ROW_LENGTH);
tile.y = TILE_SIZE * Math.floor(tilesInWorld.length / ROW_LENGTH);