Flash - Pause Game ActionScript 3 - actionscript-3

I'm only a beginner and this code is somewhere in the internet that I just want to learn
This is a snake game, I want to pause a game using spacebar keyboard
I don't know how to pause a game someone please help
import flash.ui.*;
public class Snake extends MovieClip
{
private var _Paused:Boolean = false
private var score, life, framesElapsed:Number;
private var p1speedX, p1speedY:Number;
private var spacePressed, readyToMove, gotoWin, gotoLose:Boolean;
private var left,right,up,down:Boolean;
private var snakes:Array;
private var mcFood:Food;
public function Snake()
{
}
//All Start Functions
public function startMenu()
{
stop();
btnStartGame.addEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.addEventListener(MouseEvent.CLICK, gotoHowToPlay);
}
public function startHowToPlay()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startWin()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startLose()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startGame()
{
score = 0;
life = 3;
framesElapsed = 0;
p1speedX = 1; //snakek starts moving right
p1speedY = 0;
up = false;
down = false;
left = false;
right = false;
spacePressed = false;
readyToMove = false;
gotoWin = false;
gotoLose = false;
snakes = new Array();
//Create 1st body part of snake and push it into the array
var snakeHead = new SnakePart();
snakeHead.x = 400;
snakeHead.y = 300;
snakes.push(snakeHead);
addChild(snakeHead);
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.focus = this;
}
//All Goto Functions
private function gotoStartGame(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("game");
}
private function gotoHowToPlay(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("howtoplay");
}
private function gotoMenu(evt:MouseEvent)
{
btnBack.removeEventListener(MouseEvent.CLICK, gotoMenu);
gotoAndStop("menu");
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
//1st Player Left Key
left = true;
}
else if (evt.keyCode == Keyboard.D)
{
//1st Player Right Key
right = true;
}
if (evt.keyCode == Keyboard.W)
{
//1st Player Up Key
up = true;
}
else if (evt.keyCode == Keyboard.S)
{
//1st Player Down Key
down = true;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = true;
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
left = false;
}
else if (evt.keyCode == Keyboard.D)
{
right = false;
}
else if (evt.keyCode == Keyboard.W)
{
up = false;
}
else if (evt.keyCode == Keyboard.S)
{
down = false;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = false;
}
}
public function update(evt:Event)
{
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
private function handleUserInput()
{
//Handle player 1 position
//if player wants to move left but snake is not
//already moving right
if (left && (p1speedX != 1))
{
p1speedX = -1;
p1speedY = 0;
}
//if player wants to move right but snake is not
//already moving left
else if (right && (p1speedX != -1 ))
{
p1speedX = 1;
p1speedY = 0;
}
//if player wants to move up but snake is not
//already moving down
else if (up && (p1speedY != 1))
{
p1speedY = -1;
p1speedX = 0;
}
else if (down && (p1speedY != -1))
{
p1speedY = 1;
p1speedX = 0;
}
if (spacePressed)
readyToMove = true;
}
private function handleGameLogic()
{
if (!readyToMove)
return;
framesElapsed++;
//Update the new position of the snake's head
if (framesElapsed % 2 == 0)
{
//Update motion of the snake's body
for (var i = snakes.length - 1; i >= 1; i--)
{
snakes[i].x = snakes[i-1].x;
snakes[i].y = snakes[i-1].y;
}
if (p1speedX > 0)
{
snakes[0].x += 20;
}
else if (p1speedX < 0)
{
snakes[0].x -= 20;
}
else if (p1speedY > 0)
{
snakes[0].y += 20;
}
else if (p1speedY < 0)
{
snakes[0].y -= 20;
}
//Check for collisions between the snake and its own body
for (var i = snakes.length - 1; i >= 1; i--)
{
if ((snakes[0].x == snakes[i].x) &&
(snakes[0].y == snakes[i].y))
{
collided();
break;
}
}
}
//Check for collisions between the snake and the walls
if (snakes[0].y < 0)
{
collided();
}
else if (snakes[0].x > 800)
{
collided();
}
else if (snakes[0].x < 0)
{
collided();
}
else if (snakes[0].y > 600)
{
collided();
}
//Add new food items
if (mcFood == null)
{
//Create a new food item
mcFood = new Food();
mcFood.x = Math.random() * 700 + 50;
mcFood.y = Math.random() * 500 + 50;
addChild(mcFood);
}
//Check for collisions between food item and Snake
if (mcFood != null)
{
if (snakes[0].hitTestObject(mcFood))
{
//Add score
score += 100;
if (score >= 5000)
gotoWin = true;
removeChild(mcFood);
mcFood = null;
//Add a body
var newPart = new SnakePart();
newPart.x = snakes[snakes.length-1].x;
newPart.y = snakes[snakes.length-1].y;
snakes.push(newPart);
addChild(newPart);
}
}
}
private function handleDraw()
{
//Handle display
if (!readyToMove)
txtHitSpaceBar.visible = true;
else
txtHitSpaceBar.visible = false;
txtScoreP1.text = String(score);
txtLife.text = String(life);
}
private function triggerGoToWin()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("win");
}
private function triggerGoToLose()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("lose");
}
//Misc Functions
private function resetGame()
{
//remove all food
removeChild(mcFood);
mcFood = null;
//remove all of snake body except first
for (var i = snakes.length - 1; i >= 1; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
//Center the snake's head
snakes[0].x = 400;
snakes[0].y = 300;
readyToMove = false;
}
private function clearGame()
{
//remove all food
if (mcFood != null)
{
removeChild(mcFood);
mcFood = null;
}
//remove all of snake body
for (var i = snakes.length - 1; i >= 0; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
}
private function collided()
{
life -= 1;
if (life > 0)
resetGame();
else
gotoLose = true;
}
}
}//end class
//end package

There are a few possibilities how to pause a game.
You already have a boolean variable called _Paused, this will help us to determine when to pause the execution of the game.
Change the contents of keyDownHandler(evt) to the following:
private function keyDownHandler(evt:KeyboardEvent)
{
...
//leave the if conditionals for movement as they are
if (evt.keyCode == Keyboard.SPACE)
{
if(_Pause == true){
_Pause = false;
}else{
_Pause = true;
}
}
}
The above code will toggle between a Paused state and the Game state. When the game first starts, the _Paused variable is false. Once you press Space on your keyboard, the if condition will check what state you need to be in. So at the very first time, _Paused will be set to true. if you press space again, it will set it to false again. Simple, right?
Now, you have an EventListener for ENTER_FRAME called update that executes for every frame. This function is responsible that things, well, work. You can see that it calls different functions that draw stuff on the screen or handle game logic. So, what would happen if you don't call this function? The game would stop. So we need a way to not call those functions when you are in your pause state. Again, this is very simple.
Change the contents of update(evt) to the following:
public function update(evt:Event)
{
if(_Paused == false){
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
}
Now the functions will only be called when your _Paused variable is set to false.
I hope this helped you with your studying, although this is very basic stuff. Maybe you should try smaller steps first? Programming games can be pretty complex for beginner who have no experience with coding whatsoever.

Related

How can I change Nested Class in actionscript 3

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

How do I call methods and properties from parent classes?

I'm new here (and also relatively new with AS3 as well), so bear with me.
I've only discovered OOP 2 weeks ago, and before then, I knew only the most rudimentary knowledge of AS3. So I did make a lot of improvement, but one thing's been bugging me.
I can never seem to call functions and methods from parent classes. Even with setters and getters, the child class always gives me an output error. It looks something like this.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Axiom/clicked()
This is an AS3 project that I'm working on right now that is giving me this problem.
Here's some basic background of the project.
I have the main class, called Main, and some other classes, called Axiom and Textbox. Main creates Axiom into a movieclip (background) that's already present on the stage. Axiom creates Textbox when clicked. Axiom calls a method called mouseClick from Main (plays a sound), and Textbox calls some properties from Axiom (text for the textbox).
I have attempted to use
MovieClip(this.parent).mouseClick();
and declaring a new variable in the child class, like this.
private var main:Main;
...
main.mouseClick();
And this leads me to question - what am I doing wrong, and how should I do it properly?
Here are the classes for reference.
Main.as
package {
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Mouse;
import flash.events.MouseEvent;
public class Main extends MovieClip {
// sound
private var music:Music = new Music();
private var clickSound:Click = new Click();
// instructions
private var instructions:Instructions = new Instructions();
// mouse
private var cursor:Cursor = new Cursor();
// player
private var player:Player = new Player();
private var animationState:String = "standing";
private var directionState:String = "right";
// Axiom
private var axiom:Axiom = new Axiom();
// movement
private var rightPressed:Boolean = false;
private var leftPressed:Boolean = false;
private var upPressed:Boolean = false;
private var downPressed:Boolean = false;
private var xMovement:Number = 0;
private var yMovement:Number = 0;
private var speed:Number = 22;
private var friction:Number = 0.9;
private var rDoubleTapCounter:int = 0;
private var lDoubleTapCounter:int = 0;
private var dDoubleTapCounter:int = 0;
private var uDoubleTapCounter:int = 0;
private var doubleTapCounterMax:int = 5;
private var running:Boolean = false;
public function Main() {
// constructor code
// mouse
stage.addChild(cursor);
cursor.mouseEnabled = false;
Mouse.hide();
// instructions
instructions.x = 640;
instructions.y = 120;
stage.addChild(instructions);
// add player
player.x = 642;
player.y = 448.95;
player.gotoAndStop(directionState);
player.right.gotoAndStop(animationState);
addChild(player);
// add Axiom
axiom.x = 300;
axiom.y = -150;
back.addChild(axiom);
// keyboard events
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
// music
music.play(0, int.MAX_VALUE);
// loop
stage.addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void {
// set mouse
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
// set Movement to speed
if (rightPressed) {
if (upPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * -2;
} else {
xMovement = speed;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * 2;
} else {
xMovement = speed;
yMovement = speed;
}
} else if (running || rDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * 2;
} else {
xMovement = speed;
}
} else if (leftPressed) {
if (upPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * -2;
} else {
xMovement = speed * -1;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * 2;
} else {
xMovement = speed * -1;
yMovement = speed;
}
} else if (running || lDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * -2;
} else {
xMovement = speed * -1;
}
} else if (downPressed) {
if (dDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
} else if (upPressed) {
if (uDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
}
// double tap counter
if (rightPressed == false) {
rDoubleTapCounter++;
}
if (leftPressed == false) {
lDoubleTapCounter++;
}
if (downPressed == false) {
dDoubleTapCounter++;
}
if (upPressed == false) {
uDoubleTapCounter++;
}
// change labels
if (player.currentLabel != animationState) {
player.right.gotoAndStop(animationState);
}
// friction
xMovement *= friction;
yMovement *= friction;
// animationState and stop
if (Math.abs(xMovement) > 1) {
if (Math.abs(xMovement) > 22) {
animationState = "running";
running = true;
} else {
animationState = "trotting";
running = false;
}
} else {
animationState = "standing";
xMovement = 0;
}
// right or left facing
if (xMovement > 0) {
player.scaleX = 1;
} else if (xMovement < 0) {
player.scaleX = -1;
}
//movement
if (back.x >= back.width / 2 - 50) {
if (player.x >= 642 && xMovement > 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x <= player.width / 2 && xMovement < 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else if (back.x <= 1280 - back.width / 2 + 50) {
if (player.x <= 642 - 30 && xMovement < 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x >= 1280 + 30 - player.width / 2 && xMovement > 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else {
back.x -= xMovement;
}
}
private function keyPressed(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = true;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = true;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = true;
} else if (e.keyCode == Keyboard.UP) {
upPressed = true;
}
}
private function keyReleased(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = false;
rDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = false;
lDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = false;
dDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.UP) {
upPressed = false;
uDoubleTapCounter = 0;
}
}
public function mouseClick():void {
clickSound.play();
}
}
}
Axiom.as
package {
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main;
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
main.mouseClick();
stage.addChild(speechBox);
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
Textbox.as
package {
import flash.events.MouseEvent;
import flash.display.MovieClip;
import com.greensock.TweenLite;
public class Textbox extends MovieClip{
private var axiom:Axiom;
private var main:Main;
public function Textbox() {
// constructor code
this.x = 40;
this.y = 360;
this.textBox.text = axiom.words;
TweenLite.from(this, 0.3, {x: "10", alpha: 0});
this.addEventListener(MouseEvent.CLICK, nextPage);
}
private function nextPage(e:MouseEvent):void{
main.mouseClick();
TweenLite.to(this, 0.3, {x: "-10", alpha: 0});
MovieClip(this.parent).removeThis();
}
}
}
Instead of trying to call functions of the parent (rarely a good idea), use Events instead.
In your Axiom Class:
package {
...import statements
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main; //this shouldn't be here, ideally, Axiom knows NOTHING about the main class.
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
//main.mouseClick(); // unneccesary
dispatchEvent(e); //the event you caught by performing a click will be dispatched again, so that the parent can react to it
stage.addChild(speechBox); //Axiom might not have access to the stage, addChild would suffice
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
and in your Main Class
axiom.addEventListener(MouseEvent.CLICK, onAximClicked);
private function onAxiomClicked(e:MouseEvent):void{
//now you can use the parents (in this case an Object of the Main class) functions
mouseClick();
}

To much FPS drop

http://www.fastswf.com/USUAp00
When i scale my procedural generated map based off a perlin noise map to a bigger size, so i can place a character on the map and actually navigate it (moving the map around the player instead of the player around the map), it gets major fps drop.
Test for yourself with the provided link, the higher the scale or map width/height is increased the more it lags while walking. I understand this is allot of data blocks to move
Is there a better way to go about moving my player around?
Would adding the spawned objects to an object pool help? I don't think it would
Is it possible to split the map into segments after generation and load certain segments based off your x,y?
World class: //handles spawning the map
http://pastebin.com/CfMDBWeR
Level class: // handles moving the map around
public class Level extends MovieClip
{
var world:World;
protected var goin:Vector.<int> = new Vector.<int>();
protected var moveSpeed:int;
protected var MAP_SCALE:int;
public function Level()
{
MAP_SCALE = GlobalCode.MAP_SCALE;
trace("level")
for(var i:int = 0; i < 4; i++){
goin[i]=0;
}
world = new World(this);
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
moveSpeed = 10;
// constructor code
}
protected function init(e:Event)
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
protected function cleanUp(e:Event)
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
protected function keyPressed(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.W)
{
goin[0] = 1;
}
if (k.keyCode == Keyboard.S)
{
goin[1] = 1;
}
if (k.keyCode == Keyboard.A)
{
goin[2] = 1;
}
if (k.keyCode == Keyboard.D)
{
goin[3] = 1;
}
}
protected function MovePlayer(){
if (goin[0] == 1)
{
world.worldTiles.y += moveSpeed;
}
if (goin[1] == 1)
{
world.worldTiles.y -= moveSpeed;
}
if (goin[2] == 1)
{
world.worldTiles.x += moveSpeed;
}
if (goin[3] == 1)
{
world.worldTiles.x -= moveSpeed;
}
}
protected function keyReleased(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.W)
{
goin[0] = 0;
}
if (k.keyCode == Keyboard.S)
{
goin[1] = 0;
}
if (k.keyCode == Keyboard.A)
{
goin[2] = 0;
}
if (k.keyCode == Keyboard.D)
{
goin[3] = 0;
}
}
public function update(e:Event)
{
world.worldTiles.scaleX = MAP_SCALE;
world.worldTiles.scaleY = MAP_SCALE;
MovePlayer();
}
}
Stage Class: The class actually connected to the stage, handles frame switching
public class Stage extends MovieClip {
private var targetFrame:String;
public function Stage() {
targetFrame = "Menu";
// constructor code
}
private function gotoLabel(desiredLabel:String)
{
for (var i=0; i<currentLabels.length; i++)
{
if (currentLabels[i].name == desiredLabel)
{
gotoAndPlay(desiredLabel);
return;
}
}
trace("Requested frame missing!");
}
public function generateMap(m:MouseEvent){
GlobalCode.TILE_SIZE = int(tileSizeText.text);
GlobalCode.MAP_HEIGHT = int(mapHeightText.text);
GlobalCode.MAP_WIDTH = int(mapWidthText.text);
GlobalCode.MAP_SCALE = int(mapScaleText.text);
gotoLabel("Game");
}
private function doneLoading(m:MouseEvent)
{
//set targetFrame
gotoLabel("Menu");
}
}

Assist with game logic please, if statements (maths vs hitTestPoint)

I've got an enemy and I will like this enemy to walk up to the player when it sees the hero.
if(enemy is walking right && hero is in the range of the enemy)
{ enemy walk towards player
if(enemy touches player)
{enemy attacks //enemies goes straight through the player and ends up on the left side of player}
if(enemy is walking left && hero is in the range of the enemy)
{ enemy walk towards player
if(enemy touches player)
{enemy attacks //enemies goes straight through the player and ends up on the right t side of player}
This is the pseudo code and from this I initiated the code below
for (var o:int = 0; o < aHellHoundArray.length; o++)
{
//var currentHound:HellHound = aHellHoundArray[o];
var hound:HellHound = aHellHoundArray[o];
hound.hellLoop();
if (_character.x + 150 < hound.x && _character.x > hound.x - 600)
{
hound.moveLeft = true;
hound.moveRight = false;
}
else
if (_character.x + 50 < hound.x && _character.x > hound.x - 200 && rightKey || !rightKey)
{
hound.moveRight = false;
hound.moveLeft = false;
hound.attackLeft = true;
trace("attack");
}
else
{
hound.attackLeft = false;
}
This is the hound class
/**
* ...
* #author Moynul Hussain
*/
public class HellHound extends MovieClip
{
TweenPlugin.activate([BlurFilterPlugin]);
public var movementSpeed:Number = 3;
public var moveLeft:Boolean;
public var moveRight:Boolean;
public var attack:Boolean;
public var attackLeft:Boolean;
private var resetPos:Point;
private var DashAmount:Number = 20;
public function HellHound()
{
addEventListener(Event.ADDED_TO_STAGE, init)
}
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
resetPos = new Point(x, y);
}
public function reset():void
{
x = resetPos.x;
y = resetPos.y;
}
public function hellLoop():void
{
if (attackLeft)
{
TweenMax.to(this, 0.25, { blurFilter: { blurX:20 }} );
TweenMax.to(this, 1, { x:"-100" } );
}
if (!attackLeft)
{
TweenMax.to(this, 0.5, { blurFilter: { blurX:0, blurY:0 }} );
}
if (moveLeft)
{
this.x -= 2;
this.scaleX = 1;
this.gotoAndStop("run");
}
if (moveRight)
{
this.x += 2;
this.scaleX = -1;
this.gotoAndStop("run");
}
if (!moveLeft && !moveLeft && !attack)
{
// TweenLite.to(this,0,{blurFilter:{blurX:0}});
// TweenLite.to(this,0,{blurFilter:{blurY:1000}});
TweenMax.to(this, 0.5, { blurFilter: { blurX:0, blurY:0 }} );
}
}
public function dontMove():void
{
moveLeft = false;
moveRight = false;
}
}
}
The problem is that when the the hound passes the player it is still going left. Because attack Left is still true.
I've tried doing this
if (_character.x + 150 < hound.x && _character.x > hound.x - 600)
{
hound.moveLeft = true;
hound.moveRight = false;
}
else
if (_character.x + 50 < hound.x && _character.x > hound.x - 200 && rightKey || !rightKey)
{
hound.moveRight = false;
hound.moveLeft = false;
hound.attackLeft = true;
trace("attack");
}
else
{
hound.attackLeft = false;
}
to make it false, but no dice.
Any tips of directions,
I want to stop the hound from attacking when he's gone through the player
Here:
if (attackLeft)
{
TweenMax.to(this, 0.25, { blurFilter: { blurX:20 }} );
TweenMax.to(this, 1, { x:"-100" } );
}
You're handling/consuming the attack at this point, so you should then set attackLeft = false at the end.
Another small point:
if (attackLeft)
{ ... }
if (!attackLeft)
{ ... }
You should change this to
if (attackLeft)
{ ... }
else
{ ... }
since it's only ever going to execute one or the other block of code and this will save you evaluating attackLeft twice. It's a trivial difference in this case but is good practice for when it does matter.

AS3 error 1084 syntax error expecting rightparen before dot

i am new to this whole as3 thing and i am struggling immensely. I have been sat for the last two days trying to do something i can imaging to be simple to everyone else reading this. I am trying to create a game where i have a skate boarder controlled by the keyboard keys. However when i type this code in i am getting a 1084 error please help before i throw my laptop out the window. Thanks!!
package {
import flash.display.*;
import flash.events.*;enter code here
public class skatefate extends MovieClip {
var the_skater:Sprite = new Sprite();
the_skater.addChild:(skater);
var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var moveDown:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
stage.addEventListener(Event.ENTER_FRAME, moveskater);
function keyPressedDown(event:KeyboardEvent) {
if (event.keyCode == 37) {
moveLeft = true;
} else if (event.keyCode == 39) {
moveRight = true;
} else if (event.keyCode == 65) {
moveUp = true;
} else if (event.keyCode == 90) {
moveDown = true;
}
}
function keyPressedUp(event:KeyboardEvent) {
if (event.keyCode == 37) {
moveLeft = false;
} else if (event.keyCode == 39) {
moveRight = false;
} else if (event.keyCode == 65) {
moveUp = false;
} else if (event.keyCode == 90) {
moveDown = false;
}
}
function moveskater(event:Event) {
var speed:uint = 20;
if (moveLeft) {
skater.x -= speed;
if (skater.x < 0){
skater.x = 800;
}
}
}
if (moveRight) {
skater.x += speed;
if (skater.x > 800){
skater.x = 0;
}
}
if (moveUp) {
skater.y -= speed;
if (skater.y > 0){
skater.y = 0;
}
}
if (moveDown) {
skater.y += speed;
if (skater.y > 0){
skater.y = 0;
}
}
I tried your code but didn't get your error. Your sample throws other errors & problems.
So my advice is these two things..
The correct to construct your code...
package
{
//IMPORTS go here
//Declare your Class
public class skatefate extends MovieClip
{
//VARS go here
//*******************************************************************
//note: later you may also add other VARS inside functions as needed
//(but were not originally put (declared) in this section)
//*******************************************************************
//Declare main function of your Class (must have same name as Class (.as)
public function skatefate()
{
//Constructor code here
//************************************************************************
// Your main program code and related functions (K/board etc) go here and
// will reference your VARS declared above in public Class construction)
//************************************************************************
} //End of (public) Function
} //End of (public) Class
} //End of Package
Just incase you still struggle, this edit of your code shown should compile. From there you can study & learn. Hopefully one more laptop will survive in this cruel world.
package
{
import flash.display.*;
import flash.events.*; //enter code here
//Declare your Class
public class skatefate extends MovieClip {
var the_skater:Sprite = new Sprite();
var skater:Sprite = new Sprite(); //hide line if skater exists already (i.e in Library)
var speed:uint = 20;
//Declare main function of your Class
public function skatefate ()
{
var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var moveDown:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
stage.addEventListener(Event.ENTER_FRAME, moveskater);
the_skater.addChild(skater);
addChild(the_skater); //adds to stage
function keyPressedDown (event:KeyboardEvent)
{
if (event.keyCode == 37) { moveLeft = true; }
else if (event.keyCode == 39) { moveRight = true; }
else if (event.keyCode == 65) { moveUp = true; }
else if (event.keyCode == 90) { moveDown = true; }
}
function keyPressedUp (event:KeyboardEvent)
{
if (event.keyCode == 37) { moveLeft = false; }
else if (event.keyCode == 39) { moveRight = false; }
else if (event.keyCode == 65) { moveUp = false; }
else if (event.keyCode == 90) { moveDown = false; }
}
function moveskater(event:Event)
{
//var speed:uint = 20; //already declared at top
//speed = 20; // later change 'speed' this way by updating number
if (moveLeft) {
skater.x -= speed;
if (skater.x < 0)
{ skater.x = 800; }
}
if (moveRight) {
skater.x += speed;
if (skater.x > 800)
{ skater.x = 0; }
}
if (moveUp) {
skater.y -= speed;
if (skater.y > 0)
{ skater.y = 0; }
}
if (moveDown) { skater.y += speed;
if (skater.y > 0)
{ skater.y = 0; }
}
} //close 'moveskater' function
} //End of your (public) Function
} //End of your (public) Class
} //End of Package
Hope it helps. Ask for advice in the comments and don't forget to tick as "correct answer" if it works for you. That's how we say "Thanks" on Stack Overflow.