procedural generating terrain - actionscript-3

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);

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; }
}
}

How do I remove eventlisteners and objects from an array upon game completion?

I have written a drag and drop game and, for the most part, it works.
It runs and does what I need it to do.
However, I cannot figure out two things.
How to remove the toy objects from the screen and re-add them after game over.
How to remove the event listeners for dragging/collision action after game over has initiated.
At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed.
Does anyone have any idea what I am doing wrong?
I would love to figure this out but it is driving me crazy.
Any help would be great.
Here is my code ...
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.Font;
import flash.filters.GlowFilter;
public class MainGame extends MovieClip {
const BG_SPEED:int = 5;
const BG_MIN:int = -550;
const BG_MAX:int = 0;
const PBG_SPEED:int = 3;
var bg:BackGround = new BackGround;
var paraBg:ParaBg = new ParaBg;
var toybox:TargetBox = new TargetBox;
var toy:Toy = new Toy;
var tryAgain:TryAgain = new TryAgain;
var cheer:Cheer = new Cheer;
var eightBit:EightBit = new EightBit;
var countDown:Number = 30;
var myTimer:Timer = new Timer(1000, 30);
var myText:TextField = new TextField;
var myText2:TextField = new TextField;
var myTextFormat:TextFormat = new TextFormat;
var myTextFormat2:TextFormat = new TextFormat;
var font1:Font1 = new Font1;
var kids:Kids = new Kids;
var count:int = 0;
var finalScore:int = 0;
var score:Number = 0;
var toy1:Toy1 = new Toy1;
var toy2:Toy2 = new Toy2;
var toy3:Toy3 = new Toy3;
var toy4:Toy4 = new Toy4;
var toy5:Toy5 = new Toy5;
var toy6:Toy6 = new Toy6;
var toy7:Toy7 = new Toy7;
var toy8:Toy8 = new Toy8;
var toy9:Toy9 = new Toy9;
var toy10:Toy10 = new Toy10;
var toy11:Toy11 = new Toy11;
var toy12:Toy12 = new Toy12;
var toy13:Toy13 = new Toy13;
var toy14:Toy14 = new Toy14;
var toy15:Toy15 = new Toy15;
var toy16:Toy16 = new Toy16;
var toy17:Toy17 = new Toy17;
var toy18:Toy18 = new Toy18;
var toy19:Toy19 = new Toy19;
var toy20:Toy20 = new Toy20;
var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20);
public function mainGame():void
{
trace("HI");
eightBit.play(0, 9999);
addChildAt(paraBg, 0);
addChildAt(bg, 1);
addChildAt(kids, 2);
kids.x = 310;
kids.y = 200;
addChild(toy);
toy.x = 306;
toy.y = 133;
addChild(toybox);
toybox.x = 295;
toybox.y = 90;
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
for (var i:int = 0; i < toyArray.length; i++)
{
addToys(1140 * Math.random() + 20, 170 * Math.random() + 230);
}
}
public function bgScroll (e:Event)
{
stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.start();
e.target.addEventListener(Event.ENTER_FRAME, collision);
if (stage.mouseX > 600 && bg.x > BG_MIN)
{
bg.x -= BG_SPEED;
paraBg.x -= PBG_SPEED;
for (var m:int=0; m< toyArray.length; m++)
{
(toyArray[m] as MovieClip).x -=BG_SPEED
}
}
else if (stage.mouseX < 50 && bg.x < BG_MAX)
{
bg.x += BG_SPEED;
paraBg.x += PBG_SPEED;
for (var j:int=0; j< toyArray.length; j++)
{
(toyArray[j] as MovieClip).x +=BG_SPEED
}
}
for (var k:int = 0; k < toyArray.length; k++)
{
toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab);
}
bg.addEventListener(Event.ENTER_FRAME, bgScroll);
} // End of BGScroll
public function collision (e:Event)
{
for (var l:int=0; l< toyArray.length; l++)
{
if (toyArray[l].hitTestObject(toy))
{
removeChild(toyArray[l]);
toyArray[l].x=100000;
toybox.gotoAndPlay(2);
cheer.play(1, 1);
score = score + 10;
trace(score);
}
if (score == 200)
{
timerDone();
myTimer.stop();
}
}
}
public function arrayGrab(e:MouseEvent)
{
e.target.startDrag();
}
public function arrayDrop(e:MouseEvent)
{
stopDrag();
}
public function resetGame(e:Event):void {
trace("CLICK");
countDown = 30;
myText.text = "0" + countDown.toString();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.reset();
removeChild(tryAgain);
myText2.visible = false;
score = 0;
}
public function countdown(e:TimerEvent):void
{
if (countDown > 0)
{
countDown--;
}
if (countDown < 10)
{
myText.text = "0" + countDown.toString();
myText.x = 270;
displayText();
}
else if (countDown < 20 && countDown > 9)
{
myText.text = countDown.toString();
myText.x = 280;
displayText();
}
else
{
myText.text = countDown.toString();
myText.x = 270;
displayText();
}
} // end of countdown function
public function displayText():void
{
myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)];
addChild(myText);
myText.width = 500, myText.height = 50, myText.y = 10;
myTextFormat.size = 50, myTextFormat.font = font1.fontName;
myText.setTextFormat(myTextFormat);
}
public function displayText2():void
{ myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)];
addChild(myText2);
myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200;
myTextFormat2.size = 30, myTextFormat2.font = font1.fontName;
myText2.setTextFormat(myTextFormat2);
}
public function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
addChild(tryAgain);
tryAgain.x = 300;
tryAgain.y = 300;
tryAgain.addEventListener(MouseEvent.CLICK, resetGame);
}
} // End of class
} //End of package
Nevermind ... solved it.
Easiest was was to change
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
To
function addToys(xpos:int, ypos:int)
{
stage.addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
And then, in the timerDone function I added thisif statement ...
for (var m = 0; m < toyArray.length; m++) {
if (stage.contains(toyArray[m])) {
stage.removeChild(toyArray[m]);
}
Worked a treat!

AS3 - Restart Loop Error

I have now figured out that After I restart my game The Enter_frame function is not looping? why is that.
Enter_Frame:
public function enter_frame(e:Event)
{
trace("rGame = " + rGame);
_Menu();
if(mGameStart)
{
//Stage & Players
_PlayerStart();
_PlayerCon();
_MoveStage();
}
if(rGame)
{
_PlayerCon();
trace("_PlayerCon(): Done");
_MoveStage();
}
if(Game_Over)
{
mGameStart = false;
GameOver();
}
}
Pipe_Spawn:
private function eSpawn()
{
for(var i:int = 0; i < ePipeMax; i++)
{
var _Pipe:EPipe = new EPipe;
_Pipe.x = (i * 250) + 640;
_Pipe.y = Math.random() * 90;
PipeLayer.addChild(_Pipe);
}
}
Pipe_Move:
public function _MoveStage():void
{
//Pipes Move
for (var i:int; i < vPipeMax; i++)
{
var _Pipe = PipeLayer.getChildAt(i);
if(_Pipe.hitTestPoint(_Player.x, _Player.y, true))
{
blink = true;
Remove(_White);
Game_Over = true;
}
else
{
if(_Pipe.x < 241 && _Pipe.x > 234){
ScoreReady = true;
}
else
{
ScoreReady = false;
two = true;
}
if(ScoreReady && two)
{
Score++;
Scores.text = Score.toString();
two = false;
}
if(_Pipe.x <= -20)
{
_Pipe.x = 640 + 100;
_Pipe.y = Math.random()*90;
}
_Pipe.x -= xSpeed;
}
}
}
Game_Restart:
public function restartButton(m:MouseEvent)
{
GOSign.y = 1000;
R_Button.y = 1000;
Scores.y = 105.65;
HighScore.x = 500;
ScoreReady = false;
two = true;
HighScore5();
_Player.x = 240;
_Player.y = 320;
//This is where I restart the position of the pipes
for (var i:int = 0; i < vPipeMax; i++)
{
var _Pipe = PipeLayer.getChildAt(i);
_Pipe.x = (i * 250) + 640;
_Pipe.y = Math.random() * 90;
}
rGame = true;
}
Iv been at this for about two weeks and can not fix it. Thank you for reading.
I have found my problem. It was a VERY stupid mistake and I cant believe it took me this long to figure it out. I forgot to reset a variable ~facepalm~. I guess you learn from your mistakes lol

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.

how can i make this papervision3d code work?

This code works but it does display the cube as the first code and the view, zoom and interactivity is different, so i wanted the cube to be displayed as in the first code with the same features.
first code is here: http://papervision2.com/10-advanced-interactivity/
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import org.papervision3d.materials.ColorMaterial;
import org.papervision3d.materials.MovieMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.view.BasicView;
public class Main extends BasicView
{
protected var cube:Cube;
protected var interactiveMats:Array;
protected var materialsList:MaterialsList;
protected var targetrotationX:Number;
protected var targetrotationY:Number;
protected var targetrotationZ:Number;
protected var tweening:Boolean;
public function Main():void
{
super();
init();
}
protected function init():void
{
createChildren();
startRendering();
}
protected function createChildren():void
{
//Set the viewport to interactive
viewport.interactive = true;
//Create Materials:
materialsList = new MaterialsList();
interactiveMats = ["front", "back", "left", "right", "bottom", "top"];
var colorsArray:Array = [0x76b6f8, 0x4291e1, 0x1f73c8, 0xe77111, 0xe8914c, 0xfad2b2];
for (var i:int = 0; i < interactiveMats.length; i++)
{
//Create a color box so we can use our MouseEvents
var colorBox:Sprite = new Sprite();
colorBox.graphics.beginFill(colorsArray[i]);
colorBox.graphics.drawRect(0, 0, 100, 100);
colorBox.graphics.endFill();
colorBox.name = interactiveMats[i];
//Add a textField for reference
var textField:TextField = new TextField()
colorBox.addChild(textField)
textField.text = interactiveMats[i];
//Add a MouseEvent to the Sprite
colorBox.mouseChildren = false;
colorBox.addEventListener(MouseEvent.CLICK, onMovieMatClicked);
//Create the MovieMat
var movieMat:MovieMaterial = new MovieMaterial(colorBox, true, true);
movieMat.interactive = true;
movieMat.smooth = true;
materialsList.addMaterial(movieMat, interactiveMats[i]);
}
//Create Cube
cube = new Cube(materialsList, 100, 100, 100);
//Add cube to the scene
scene.addChild(cube);
}
protected function onMovieMatClicked(evt:MouseEvent):void
{
if (tweening)
{
// Let it rotate again
tweening = false;
}
else
{
switch(evt.target.name) {
case "front":
targetrotationX = 0;
targetrotationY = 180;
targetrotationZ = 0;
tweening = true;
break;
case "back":
targetrotationX = 0;
targetrotationY = 0;
targetrotationZ = 0;
tweening = true;
break;
case "left":
targetrotationX = 0;
targetrotationY = -90;
targetrotationZ = 0;
tweening = true;
break;
case "right":
targetrotationX = 0;
targetrotationY = 90;
targetrotationZ = 0;
tweening = true;
break;
case "top":
targetrotationX = -90;
targetrotationY = 0;
targetrotationZ = 0;
tweening = true;
break;
case "bottom":
targetrotationX = 90;
targetrotationY = 0;
targetrotationZ = 180;
tweening = true;
break;
}
}
}
override protected function onRenderTick(event:Event = null):void
{
super.onRenderTick(event);
if (tweening) {
// If a face has been clicked
if (camera.zoom <230) {
// If the camera isn't zoomed enough then zoom in a bit more:
camera.zoom += Math.sqrt(230-camera.zoom)/5;
}
// Test each rotation and rotate it towards the target rotation:
// X axis:
if (cube.rotationX < targetrotationX)
{
cube.rotationX += Math.sqrt(targetrotationX-cube.rotationX);
cube.rotationX = Math.round(cube.rotationX);
}
else if (cube.rotationX > targetrotationX)
{
cube.rotationX -= Math.sqrt(cube.rotationX-targetrotationX);
cube.rotationX = Math.round(cube.rotationX);
}
// Y axis:
if (cube.rotationY < targetrotationY)
{
cube.rotationY += Math.sqrt(targetrotationY-cube.rotationY);
cube.rotationY = Math.round(cube.rotationY);
}
else if (cube.rotationY > targetrotationY)
{
cube.rotationY -= Math.sqrt(cube.rotationY-targetrotationY);
cube.rotationY = Math.round(cube.rotationY);
}
// Z axis:
if (cube.rotationZ < targetrotationZ)
{
cube.rotationZ += Math.sqrt(targetrotationZ-cube.rotationZ);
cube.rotationZ = Math.round(cube.rotationZ);
}
else if (cube.rotationZ > targetrotationZ)
{
cube.rotationZ -= Math.sqrt(cube.rotationZ-targetrotationZ);
cube.rotationZ = Math.round(cube.rotationZ);
}
}
else
{
// If the camera is zoomed in, it shouldn't be now
if (camera.zoom > 200)
{
// So zoom out a bit.
camera.zoom -= Math.sqrt(camera.zoom-2)/5;
}
// Rotate the cube a bit:
cube.rotationX += 2;
cube.rotationY += 2;
// Make sure that we dont "wind up" the rotation
if (cube.rotationX>= 360) cube.rotationX = 0;
if (cube.rotationY>= 360) cube.rotationY = 0;
}
}
}
}
code2 taken from: http://papervision2.com/advanced-interactivity/
However the article was submitted, it parsed < to < and > to >.
Do a find/replace for each of those and the bulk of the errors should go away.