Breakout game in AS3 error #2007 - actionscript-3

I came upon an error I can't fix. I'm making a game and it should say "you lose" after losing your 3 lives, but in my case everything freezes and I get an error.
TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at Fatality/enterFrameEvents()[C:\Documents and Settings\labo\Bureaublad\GIP 12 mei\Fatality.as:26]
Have a look at my code. This is the code I've written in the class
Basicly this class is a "game over" power in my breakout game. When this touches the paddle, it's game over. The problem is that it freezes after it touches the paddle instead of showing "you lose".
package
{
import flash.display.*;
import flash.events.*;
public class Fatality extends MovieClip
{
private var yspeed:Number = 1;
private var _root:MovieClip;
public function Fatality()
{
// constructor code
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
private function beginClass(event:Event):void
{
//defining _root as the document root
////je definieërt _root als het document root
_root = MovieClip(root);
}
private function enterFrameEvents(event:Event):void
{
this.y = this.y + yspeed;
if (this.hitTestObject(_root.mcPaddle))
{
this.removeEventListener(Event.ENTER_FRAME, enterFrameEvents);
this.parent.removeChild(this);
if (_root.lives == 3)
{
_root.removeChild(_root.hartje3);
_root.removeChild(_root.hartje2);
_root.removeChild(_root.hartje1);
}
else if (_root.lives == 2)
{
_root.removeChild(_root.hartje2);
_root.removeChild(_root.hartje1);
}
else if (_root.lives == 1)
{
_root.removeChild(_root.hartje1);
}
_root.gameOver = true;
//De listeners weg doen
_root.mcBall.removeEventListener(Event.ENTER_FRAME, _root.moveBall);
_root.mcPaddle.removeEventListener(Event.ENTER_FRAME, _root.movePaddle);
removeEventListener(Event.ENTER_FRAME, _root.checkLevel);
removeEventListener(Event.ENTER_FRAME, _root.updateTextFields);
//Ga naar een lose frame
_root.gotoAndStop('lose');
}
}
}
}
That last part refers to the lose frame, here is the code of the lose frame
//De lose frame
//reset het spel als je op je muis klikt
stage.addEventListener(MouseEvent.CLICK, resetGame);
function resetGame(event:MouseEvent):void{
//deze listener weg doen
stage.removeEventListener(MouseEvent.CLICK, resetGame);
//het spel resetten
gotoAndPlay(1);
}
//de eindscore laten zien
txtScore.text = "Final Score: "+score;
I would really appreciate if somebody helped me with this error because it's been annoying me quite alot, thanks.
EDIT
MAIN CODE:
import flash.events.MouseEvent;
import flash.events.Event;
stop();
//Variabelen
//Nodige variabelen voor de beweging van de bal
var ballXSpeed:Number = 8;//X Snelheid van de bal
var ballYSpeed:Number = 8;//Y Snelheid van de bal
//Hoeveel bricks er over zijn op het stage (podium)
var brickAmt:int = 0;
//Hoeveel levens je hebt
var lives:int = 3;
//Als het game over is
var gameOver:Boolean = false;
//De score van het spel
var score:int = 0;
//Eerst heb ik een een functie gemaakt waar
//al de code in zit die nodig is om het spel te starten
//dit bevat listeners, variabelen en andere dingen
function beginCode(event:MouseEvent):void
{
//doet de listener weg wanneer je klikt
stage.removeEventListener(MouseEvent.CLICK, beginCode);
//Voegt een listener toe aan de paddle
//die een functie runt elke keer als een frame voorbij is
mcPaddle.addEventListener(Event.ENTER_FRAME, movePaddle);
//Voegt een listener toe aan de ball;
//die een functie runt elke keer als een frame voorbij is
mcBall.addEventListener(Event.ENTER_FRAME, moveBall);
//Voegt een listener toe om te checken of het level voorbij is;
addEventListener(Event.ENTER_FRAME, checkLevel);
//verwijdert het "click to start" tekst
txtStart.text = '';
}
function movePaddle(event:Event):void
{
//De paddle volgt de muis
mcPaddle.x = mouseX - mcPaddle.width / 2;
//Houdt de paddle op het stage
//Als de muis te ver naar links gaat
if (mouseX < mcPaddle.width / 2)
{
//Houdt de paddle op het stage
mcPaddle.x = 0;
}
//Als de muis te ver naar rechts gaat
if (mouseX > stage.stageWidth - mcPaddle.width / 2)
{
//Houdt de paddle on stage
mcPaddle.x = stage.stageWidth - mcPaddle.width;
}
}
function ContinueGame(event:Event):void
{
mcBall.addEventListener(Event.ENTER_FRAME, moveBall);
}
function moveBall(event:Event):void
{
//Dit is de code voor de beweging van de bal
mcBall.x += ballXSpeed;//Beweegt de bal horizontaal
mcBall.y += ballYSpeed;//Beweegt de bal verticaal
//Stuitert de bal weg van de muren
if (mcBall.x >= stage.stageWidth - mcBall.width)
{
//Als de bal de rechterkant raakt
//van het scherm, en weg stuitert
ballXSpeed *= -1;
}
if (mcBall.x <= 0)
{
//Als de bal de linkerkant raakt
//van het scherm, en weg stuitert
ballXSpeed *= -1;
}
if (mcBall.y >= stage.stageHeight - mcBall.height)
{
//Als de bal de grond raakt
//stuitert het omhoog en verlies je 1 leven
//ballYSpeed *= -1;
lives--;
if (lives == 2)
{
removeChild(this.hartje3);
}
else if (lives == 1)
{
removeChild(this.hartje2);
}
else if (lives == 0)
{
removeChild(this.hartje1);
}
ballXSpeed = 8;
ballYSpeed = 8;
mcBall.x = 151.9;
mcBall.y = 264.9;
mcBall.removeEventListener(Event.ENTER_FRAME, moveBall);
stage.addEventListener(MouseEvent.CLICK, ContinueGame);
//Wanneer er geen levens meer over zijn
if (lives <= 0)
{
//het is nu game over
gameOver = true;
//De listeners weg doen
mcBall.removeEventListener(Event.ENTER_FRAME, moveBall);
mcPaddle.removeEventListener(Event.ENTER_FRAME, movePaddle);
removeEventListener(Event.ENTER_FRAME, checkLevel);
removeEventListener(Event.ENTER_FRAME, updateTextFields);
//Ga naar een lose frame
gotoAndStop('lose');
}
}
else
{
if (mcBall.y <= 0)
{
//Als de bal de bovenkant raakt van het scherm
//en stuitert terug naar beneden
ballYSpeed *= -1;
}
//Je raakt de paddle
if (mcBall.hitTestObject(mcPaddle))
{
calcBallAngle();
}
}
}
function calcBallAngle():void
{
//ballPosition is de positie van het balletje op de paddle
var ballPosition:Number = mcBall.x - mcPaddle.x;
//hitPercent converts ballPosition in een percentage
//Helemaal naar links is -0.5
//Helemaal naar rechts is 0.5
//Het midden is 0
var hitPercent:Number = (ballPosition / (mcPaddle.width - mcBall.width)) - .5;
//Neemt het hitPercent en maakt het een groter nummer zodat de bal
//werkelijk stuitert
ballXSpeed = hitPercent * 10;
//Zorgt dat het balletje terug omhoog stuitert
ballYSpeed *= -1;
}
function makeLvl():void
{//Zet de bricks op level 1
//checkt of er nog levels over zijn
if (currentLvl > lvlArray.length)
{
//het is nu game over
gameOver = true;
//de listeners weg doen
mcPaddle.removeEventListener(Event.ENTER_FRAME, movePaddle);
mcBall.removeEventListener(Event.ENTER_FRAME, moveBall);
removeEventListener(Event.ENTER_FRAME, checkLevel);
removeEventListener(Event.ENTER_FRAME, updateTextFields);
//ga naar een lose frame
gotoAndStop("win");
}
//vindt de array lengte van de level code
//De index moet currentLvl-1 zijn want:
//array indexes beginnen vanaf 0 en onze level start op 1
//onze level zal altijd 1 hoger zijn dan de index van de array
var arrayLength:int = lvlArray[currentLvl - 1].length;
//de huidige rij van bricks die we aan het maken zijn
var brickRow:int = 0;
//Een lus die dr bricks op het stage zet
for (var i:int = 0; i<arrayLength; i++)
{
//Checkt of het een brick moet zetten daar
if (lvlArray[currentLvl - 1][i] == 1)
{
//maakt een variabele aan van de brick
var brick:Brick = new Brick();
//regelt de coordinaten van de brick via de i variabele en brickRow
brick.x = 15 + (i - brickRow * 7) * 75;
brick.y = 10 + brickRow * 20;
//checkt of de huidige brick een nieuwe rij nodig heeft
for (var c:int = 1; c<=10; c++)
{
if (i == c*7-1)
{
brickRow++;
}
}
//nu zet dit de brick op het stage
addChild(brick);
}
}
}
function checkLevel(event:Event):void
{
//checkt of de bricks allemaal weg zijn
if (brickAmt == 0)
{
//reset het level door het level te verhogen
currentLvl++;
//makeLvl wordt opnieuw gerunt
//reset de tekst "click to begin"
txtStart.text = "Click To Begin";
makeLvl();
//reset de positie van het balletje en de paddle
mcBall.x = 150;
mcBall.y = 265;
mcBall.width = 10;
mcBall.height = 10;
mcPaddle.x = 230;
//al de listeners weg doen
mcPaddle.removeEventListener(Event.ENTER_FRAME, movePaddle);
mcBall.removeEventListener(Event.ENTER_FRAME, moveBall);
removeEventListener(Event.ENTER_FRAME, checkLevel);
//je "listent" voor een click van de muis om het spel terug te starten
stage.addEventListener(MouseEvent.CLICK, beginCode);
}
}
function updateTextFields(event:Event):void
{
}
//als je clickt met je muis, begint het spel
stage.addEventListener(MouseEvent.CLICK, beginCode);
//de tekst die tevoorschijn komt;
txtStart.text = "Click To Begin";
//een functie maken om de text fields te updaten
addEventListener(Event.ENTER_FRAME, updateTextFields);
//het level maken
makeLvl();
pauseButton.addEventListener(MouseEvent.CLICK, pauseGame);
function pauseGame(e:MouseEvent):void
{
stage.frameRate = 0;
}
playButton.addEventListener(MouseEvent.CLICK, resumeGame);
function resumeGame(e:MouseEvent):void
{
stage.frameRate = 24;
}
CODE FOR THE BRICK CLASS:
//klassen moeten altijd in een packed zitten
package
{
//display elements importeren die we kunnen gebruiken in deze klasse
import flash.display.*;
import flash.events.*;
//de naam van de klasse definiëren en zeggen dat
//het de MovieClip klasse "extends",
//dat wil zeggen dat het dezelfde properties heeft als die van een movieclip
public class Brick extends MovieClip
{
//de main timeline
private var _root:MovieClip;
//alle klassen moeten een functie hebben die elke keer
//runt wanneer een instance van die klasse op het stage wordt gezet
public function Brick()
{
//deze code runt wanneer de brick op het stage wordt gezet
addEventListener(Event.ADDED, beginClass);
//enter frame code
addEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
//private functions zijn functies die je niet kan gebruiken
//vanuit de main timeline, maar enkel vanuit de klasse zelf
private function beginClass(event:Event):void
{
//je definieërt _root als het document root
_root = MovieClip(root);
//verhoogt het aantal bricks op het stage
_root.brickAmt++;
}
private function enterFrameEvents(event:Event):void
{
//controleren of de player heeft verloren
if (_root.gameOver)
{
//deze brick kapot maken
this.parent.removeChild(this);
//stoppen met deze code te runnen;
removeEventListener(Event.ENTER_FRAME, enterFrameEvents);
}
//hit testing met het balletje
if (this.hitTestObject(_root.mcBall))
{
//hierdoor stuitert het balletje verticaal
_root.ballYSpeed *= -1;
//Creeër een Power UP (Werk met een Random
//om een powerup te maken en werk met een
//tweede random om te bepalen welke power)
MakePowerUp();
//deze brick kapot maken
this.parent.removeChild(this);
//stoppen met deze code te runnen;
removeEventListener(Event.ENTER_FRAME, enterFrameEvents);
//verlaagt het aantal bricks op het stage
_root.brickAmt--;
//de score verhogen
_root.score += 10;
}
}
function MakePowerUp():void
{
//random plaatsen om te beslissen of er een power aangemaakt wordt
//en zo ja, welke
var getal = randomRange(1,40);
if (getal < 3)
{
var power:Power = new Power();
power.x = this.x + 35;
power.y = this.y + 5;
_root.addChild(power);
}
else if (getal < 6)
{
var power2:Power2 = new Power2();
power2.x = this.x + 35;
power2.y = this.y + 5;
_root.addChild(power2);
}
else if (getal < 9)
{
var mario:Enlarger = new Enlarger();
mario.x = this.x + 35;
mario.y = this.y + 5;
_root.addChild(mario);
}
else if (getal < 14)
{
var power3:Power3 = new Power3();
power3.x = this.x + 35;
power3.y = this.y + 5;
_root.addChild(power3);
}
else if (getal < 16)
{
var fat:Fatality = new Fatality();
fat.x = this.x + 35;
fat.y = this.y + 5;
_root.addChild(fat);
}
else if (getal < 20)
{
var lifesteal:Lifestealer = new Lifestealer();
lifesteal.x = this.x + 35;
lifesteal.y = this.y + 5;
_root.addChild(lifesteal);
}
}
function randomRange(minNum: Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
}
}

The error is referring to line 26:
if (this.hitTestObject(_root.mcPaddle))
The error is telling you that _root.mcPaddle is null at that point in the program.

You have an enterframe listener attached to all the bricks. They continue to fire after a gameover event. You have to remove all of them at the point you initiate a gameover condition. The trouble is, you apparently do not keep track of how many bricks are there, and what are they. I'd advise making an Array of Bricks, place them as usual, but use one single enter frame listener that will check if the ball collides with any of the bricks in turn, instead of testing against this aka a brick. This way you will have a single stationary point that will contain all the enterframe code, ease your debugging, allow yourself to expand the game functional easier, and consolidate all the code concerning game flow. For this, you will have to use a manager class, most likely Level, which you add to a frame instead of a set of bricks, and which will create the necessary amount of bricks from a data table that corresponds to a level.
If you want to do both creating a level by hand, aka placing bricks on stage, and have such a functionality, you make a container sprite, that overlaps the entirety of a level, that contains all the bricks, and that is either of Level type or extends Level, and make a Level class which will trace all its children for being of type Brick, enumerate them and add to an internal array. A sample enumerator code:
public class Level extends Sprite {
private var bricks:Array=new Array();
private var numBricks:int=0;
public function Level() {
for (var i:int=0;i<numChildren;i++) {
if (getChildAt(i) is Brick) {
numBricks++;
bricks.push(getChildAt(i));
}
}
// do the rest of initialization
addEventListener(Event.ENTER_FRAME,processLevel);
}
private function processLevel(e:Event):void {
moveBall();
movePaddle();
movePowerups();
for (var i:int=numBricks-1;i>=0;i--) {
if (bricks[i].hitTestObject(ball)) {
// process hit brick
bricks.splice(i,1); // drop a now nonexistent brick off array
numBricks--;
if (numBricks==0) { } // level won, add code to advance
// and don't forget cleanup, and return statement!
}
}
// about the same for powerups, including an array, number of powerups,
// powerups effect, etc.
}

Related

What is the role of the "class" function in my Processing sketch?

I just need a confirmation about the role of the class function in my Processing sketch. My program is a Snake (the game Snake).
I think it is used in order to connect all the points of the snake so that they can follow each other.
Or maybe it's something else. Hope you can help me out on this.
The class function appears at the end of the program.
ArrayList snake; // l'ArrayList qui va contenir les elements du serpent
int snakeTaille = 3; // la taille initial du serpent
int positionX = 0; // position sur l'axe des X de la tete du serpent
int positionY = 0; // et sur l'axe des Y
int direction = 1; // la direction initiale
Point pomme; // la position de la pomme
int colonnes = 50; // la taille de la grille notre jeu en lignes et colonnes
int lignes = 43;
int pas = 10; // le pas de la grille du jeu
int tempo = 100; // la tempo du déplacement du serpent
long dernierPas = 0;
int score = 0; // le score
int essais = 0; // le nombre d'essai
boolean commencer = false;
// la direction est codée par un nombre qui représente le Nord, Sud, Est ou Ouest
// 0 = N
// 3 = O + 1 = E
// 2 = S
import ddf.minim.*;//C'est cette instruction (que vous pouvez saisir à la main si vous le voulez) qui importera l'ensemble des fonctionnalités de la bibliothèque Minim pour les rendre accessibles à notre programme. C'est à partir de cette instruction import ddf.minim.*; que notre sketch va pouvoir jouer du son.
AudioPlayer player;
Minim minim;
void setup() {
minim = new Minim(this); // on appelle le player.
player = minim.loadFile("Mélodie snake.wav",2048); // on sélectionne la mélodie.
player.loop();//musique infiniment
size(500,500); // la taille du sketch est celle de la grille * le pas de la grille
textAlign(CENTER);
noStroke();//pas de contours
// à sa naissance le serpent est placé au centre de la grille du jeu
positionX = colonnes/2;
positionY = lignes/2;
snake = new ArrayList(); // on initialise l'ArrayList du serpent
snake.add(new Point(positionX, positionY)); // on y ajoute le premier element
// la pomme est créée à une position aléatoire
pomme = new Point((int)random(colonnes), (int)random(lignes));
dernierPas = millis();
}
void draw() {
noStroke();
background(40,150,250);
fill(0);// coloration en noir du rectangle
rect(50,430,400,500);// rectangle noir du bas
fill(120,10,60);
rect(0,430,50,75);//petit rectangle rose en bas à gauche
rect(450,430,50,75);//petit rectangle rose en bas à droite
stroke(120,10,60);//couleur de l'animation automatique
for(int i = 200; i < player.bufferSize() - 200; i++)// Endroit où se place l'animation (abcisse x)
{
float x1 = map( i, 0, player.bufferSize(), 0, width );
float x2 = map( i+1, 0, player.bufferSize(), 0, width );
line( x1, 465 + player.left.get(i)*30, x2, 465 + player.left.get(i+1)*30 );// endroit où se place l'animation (ordonnées)
line( x1, 465 + player.right.get(i)*30, x2, 465 + player.right.get(i+1)*30 );// endroit où se place l'animation (ordonnées)
}
if (commencer==false) {
fill(153,5,5);
text("Bienvenue dans SNAKE\nNouvelle partie?\nEssayez d'atteindre 15 points pour gagner !", width/2, height/2);
return;
}
if (millis()>dernierPas+tempo) { // si 'tempo' milliscondes se sont écoulées on bouge le serpent
// on determine la position de la tête en fonction de la direction
if (direction == 0) positionY -= 1; // nord
if (direction == 1) positionX += 1; // est
if (direction == 2) positionY += 1; // sud
if (direction == 3) positionX -= 1; // ouest
// si le serpent sort du cadre on perd.
if ((positionX<0)||(positionX>=colonnes)||(positionY<0)||(positionY>=lignes)) {
snake.clear(); // on vide l'ArrayList du serpent
positionX = colonnes/2; // et on repositionne la tête du serpent au centre
positionY = lignes/2;
snakeTaille = 3; // on remet le serpent a sa taille initiale
tempo = 100; // on remet le tempo a 120
essais ++;
score=0;
}
// si le serpent se mord la queue on perd aussi
for (int i = snake.size()-1; i >= 0; i--) {
Point snakeElement = (Point) snake.get(i);
if (snakeElement.touche(positionX, positionY)) { // la tête est-elle sur le même point qu'un des elements du serpent ?
snake.clear(); // on vide le arrayList du serpent
positionX = colonnes/2; // on repositionne le serpent au centre
positionY = lignes/2;
snakeTaille = 3; // on remet le serpent a sa taille initiale
tempo = 100; // on remet le tempo a 250
essais ++;
score=0;
break; // on peut sortir prématurement de la boucle 'for'
}
// quand on a atteint le nombre d'essai maximum
if (essais == 5) {
positionX = colonnes/2; // on repositionne le serpent au centre
positionY = lignes/2;
fill(153,5,5);
text("Game Over !\nVous n'avez pas réussi à atteindre les 15 points!", width/2, height/2);
player.pause(); // la musique s'arrête
return;// on stop tout pour pouvoir afficher le score final
}
}
// si le tête touche la pomme on gagne un point, une taille et on acélère
if (pomme.touche(positionX, positionY)) {
score ++; // un point de plus
snakeTaille ++; // une taille en plus
tempo -=15; // on accelere la cadence
// et on replace la pomme quelque part dans le jeu
pomme.x = (int) random(colonnes);
pomme.y = (int) random(lignes);
}
if (score == 15) {
positionX = colonnes/2; // on repositionne le serpent au centre
positionY = lignes/2;
fill(153,5,5);
text("Vous avez gagné!\nLes 15 points ont été atteints, félicitations !", width/2, height/2);
player.pause(); // la musique s'arrête
return;// on stop tout pour pouvoir afficher le score final
}
// on ajoute la tete à la l'ArrayList du serpent
Point tete = new Point(positionX, positionY);
snake.add(tete);
// on contraint la taille du serpent à 'snakeTaille' elements
if (snake.size()>snakeTaille) snake.remove(0);
dernierPas = millis();
}
noStroke();//pas de contours accentués pour le serpent
fill(255); // couleur du score.
text(score, width-120, height-10); // position du compteur du score
text("score :",width-145, height-10); // position du mot "score :"
fill(255); //couleur des essais
text (essais, width/4, height-10); // position du compteur des essais
text ("essais :", width-405, height-10); // postion du mot "essais :"
fill(104,75,64); // couleur du serpent.
//on dessine chaque elements du serpent
for (int i = snake.size()-1; i >= 0; i--) {
Point point = (Point) snake.get(i);
ellipse(point.x*pas + pas/2, point.y*pas + pas/2, pas, pas);
}
stroke(255,200,0);//les contours de la pomme sont dorés
// et on dessine la pomme en rouge
fill(255, 0, 0);
ellipse(pomme.x*pas + pas/2, pomme.y*pas + pas/2, pas, pas);
}
void keyPressed() {
// on change la direction en fonction des fleche du clavier
// mais on ne permet pas de revenir sur soi
switch(keyCode) {
case RIGHT:
if (direction!=3) direction=1;
break;
case LEFT:
if (direction!=1) direction=3;
break;
case UP:
if (direction!=2) direction=0;
break;
case DOWN:
if (direction!=0) direction=2;
break;
}
}
void mousePressed() {
commencer = true;
}
class Point {
int x; // position x
int y; // et y
Point(int _x, int _y) {
x = _x;
y = _y;
}
Boolean touche(int _x, int _y) {
return ((_x==x)&&(_y==y));
}
}
It doesn't make sense to say you have a class function- you have a class named Point.
Think about it this way: you know how to use primitive values like int and boolean. For example, an int value can hold a single integer value. But what do you do when you want a single value to be represented by multiple primitive values? For example, you might want to keep track of a single point, which is both an X and a Y value.
The answer to that question is that you use a class. Put simply, a class is a collection of values (and methods) that represents a single object. For example, your Point class represents a single point object, which is made up of an X and a Y value.
If that sounds confusing, keep in mind that you're already using the ArrayList class, and all of your code is in a PApplet class behind the scenes. I also would guess that you got this code from the internet- I suggest trying to start from scratch instead of trying to work backwards from somebody else's code.
For more info on classes, check out this tutorial I wrote, or check out the Java tutorials.
Also, note that Processing has a PVector class, so you don't really need to create your own Point class.

AS3 character movement - making the character jump

I'm making a (really) simple platform game for a school project with a little help from different online tuts.
For a couple of days I have been trying to make the character jump. I don't get any errors and if i test it with a trace statement the statement appears in the output. I tried several ways that I found in different tuts but couldn't make it work.
This is the code i've been using for my character:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class ana extends MovieClip {
private var _vx:Number;
private var _halfWidth:Number;
private var _previousKey:uint;
public var speler:ana;
// variabelen die bij de jump functie horen
var upKeyDown:Boolean = false;
var mainJumping:Boolean = false;
var jumpSpeedLimit:int = 15;
var jumpSpeed:Number = jumpSpeedLimit;
public function ana() {
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void {
this._vx = 0;
this._halfWidth = this.width / 2;
this._previousKey = Keyboard.RIGHT;
this.stop();// toegevoegd zodat de loop cycle van de speler stopt aan het begin van het spel
/*EVENT LISTENERS*/
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);
this.addEventListener(Event.ENTER_FRAME, onEnter);
this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
private function onRemovedFromStage(event:Event):void {
this.removeEventListener(Event.ENTER_FRAME, onEnter);
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
this.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
private function onKeyboardDown(event:KeyboardEvent):void {
//zorgt ervoor dat het character de juiste richting op rent
var currentKey:uint = event.keyCode;
//Voor de linker toets
if (event.keyCode == Keyboard.LEFT){
// Als de huidige toets niet gelijk is aan vorige, dan wordt het character gedraait
if (currentKey != _previousKey) {
_previousKey = currentKey;
this.scaleX *= -1;
}
// De run cycle wordt aangeroepen, de positie van het character verplaatst naar links met X frames per seconden
loopRun();
_vx = -8;
}
// voor de rechter toets
if (event.keyCode == Keyboard.RIGHT){
if (currentKey != _previousKey) {
_previousKey = currentKey;
this.scaleX *= -1;
}
// zelfde als vorige if statement, alleen -X wordt X om de richting van links naar rechts te veranderen
loopRun();
_vx = 8;
}
/*Het is me niet gelukt om de speler te laten springen*/
if (event.keyCode == Keyboard.SPACE) {
mainJump();
trace("spring");
}
/*Functie om de speler te laten springen
werkt helaas niet... krijg ook geen error messages...
heb verschillende manieren en codes geprobeert...
Deze code komt uit de volgende tutorial: http://goo.gl/S5VRd0 */
function mainJump():void{
if(!mainJumping){
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
this.y += jumpSpeed;
} else {
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
this.y += jumpSpeed;
if(this.y >= stage.stageHeight - this.height){
mainJumping = false;
this.y = stage.stageHeight - this.height;
}
}
}
}
// bron: Flash AS3 Simple Game 04: player class http://www.youtube.com/watch?v=u4dwuAUYrkg
private function onKeyboardUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT) {
_vx = 0;
gotoAndStop(1);
}
}
private function onEnter(event:Event):void {
this.x += _vx;
checkStageBoundaries();
}
private function loopRun():void {
//zorgt ervoor dat de run cycle van het character blijft 'loopen'
if (currentFrame == 12) {
gotoAndPlay(1);
}
else {
play();
}
}
private function checkStageBoundaries():void {
//controleert of de speler zich buiten de grenzen van de stage begint en blokkeerd de speler als hij de stage wil verlaten
//van volgende tutorial overgenomen: Flash as3 simple game 04: Player Class http://www.youtube.com/watch?v=u4dwuAUYrkg
if (this.x - _halfWidth < 0) {
this.x = 0 + _halfWidth;
}
else if (this.x + _halfWidth > stage.stageWidth) {
this.x = stage.stageWidth - _halfWidth;
}
}
}
}
The code is heavily commented in dutch due to the nature of the assignment.
Just in case here is my main class:
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.*;
import flash.text.*;
import flash.utils.*;
import flash.ui.*;
public class Main extends MovieClip {
/*VARIABELEN*/
public var startScreen:StartScreen; //beginscherm
public var playScreen:PlayScreen; // speel scherm
public var startBtn:StartBtn; // start knop die naar het speel scherm gaat
public var speler:ana = new ana; // speler
/*variabelen voor de diamantjes*/
public var diamant:Diamond = new Diamond;
public var diamant2:Diamond = new Diamond;
public var diamant3:Diamond = new Diamond;
public var diamant4:Diamond = new Diamond;
public var info:infoTxt = new infoTxt;
public function Main() {
//Start scherm op stage & startknop
show_startScreen(); // roept functie aan om het startscherm te laten zien
startBtn.addEventListener(MouseEvent.CLICK, playGame); //voegt muisevent toe aan de startknop
}
// speel scherm
public function show_startScreen() { // functie voor startscherm
/*variabelen voor de mc's*/
startScreen = new StartScreen(this);
startBtn = new StartBtn;
/*toevoegen startscherm en startknop*/
addChild(startScreen);
addChild(startBtn);
/*positionering startknop*/
startBtn.y = 230;
startBtn.x = 400;
}
public function playGame(event:MouseEvent) { //roept functie voor de startknop aan
play_game();
}
public function play_game() { //deze code wordt uitgevoerd nadat de playGame functie is aangeroepen
playScreen = new PlayScreen(this); //variabel voor het speel scherm
if (startScreen) { //deze code zorgt ervoor dat het beginscherm wordt verwijderd
removeChild(startScreen);
startScreen = null;
}
addChild(playScreen); //voegt speelscherm toe
addChild(speler); //voegt speler toe
addChild(info); // voegt de informatie text toe
/* positionering info text*/
info.x = 20;
info.y = 20;
/*positionering speler*/
speler.y = 400;
speler.x = 0;
/*toevoegen en positioneren van diamantjes, de y as staat al gedefinieerd in de Diamanond class*/
addChild(diamant);
diamant.x = 450;
addChild(diamant2);
diamant2.x = 570;
addChild(diamant3);
diamant3.x = 690;
addChild(diamant4);
diamant4.x = 810;
// event listener voor de speler, die wordt aangeroepen bij elk frame
speler.addEventListener(Event.ENTER_FRAME, diamondCollision);
// Collision functie, die ervoor zorgt dat de diamantjes verdwijnen als de speler ze aanraakt
// over hitTestObject staat heel veel info op internet, hier heb ik geen speciefieke tutorial voor gebruikt
// heb hitTestObject functie ook eerder gebruikt voor de groeps game
function diamondCollision (event:Event):void {
if (diamant != null) {// als diamant er nog is
if (speler.hitTestObject(diamant)){// als de speler de diamant aanraakt
removeChild(diamant);// verwijder de mc
diamant = null; // zorgt ervoor dat het niet herhaald kan worden
}
}
/*Hetzelfde voor de andere 3 diamantjes*/
if (diamant2 != null) {
if (speler.hitTestObject(diamant2)) {
removeChild(diamant2);
diamant2 = null;
}
}
if (diamant3 != null) {
if (speler.hitTestObject(diamant3)) {
removeChild(diamant3);
diamant3 = null;
}
}
if (diamant4 != null) {
if (speler.hitTestObject(diamant4)) {
removeChild(diamant4);
diamant4 = null;
}
}
}
}
}
}
I uploaded the swf file to swfcabin, so you can see the rest works fine: http://www.swfcabin.com/open/1404819729.
Can anyone help me getting my character to jump?
Thank you!
Your jumpSpeed alteration should reside in an enterframe listener, onEnter, moreover, you should relocate the mainJump() code into there, as gravity should act once per frame. Only the jump initialization code should remain in the mainJump function, that is, check if jumping, if not make it jump, assign y-speed and leave the function.
private function onEnter(event:Event):void {
this.x += _vx;
if (mainJumping) {
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
this.y+=jumpSpeed;
if(this.y >= stage.stageHeight - this.height){
mainJumping = false;
this.y = stage.stageHeight - this.height;
jumpSpeed=0;
}
}
checkStageBoundaries();
}
function mainJump():void{
if(!mainJumping){
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
this.y += jumpSpeed;
} // enough!
}

AS3: Part of code doesnt get executed

So, I need to remove my frog, from a small flash game, after 3 times moving, I'm trying to do this with 'aantalGezwommen' and a function, sadly it doesn't work with the code now.
I can't figure it out, any of you got an idea?
I have included the whole code, so if something else is wrong, please tell :)
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class KikkerOgen extends MovieClip {
var timer:Timer = new Timer(1000, 4);
var geknipperd:int = 0;
var hoevaakKnipperen:int = 0;
var aantalGezwommen:int = 0;
var score:int = 0;
//boompjes en bosjes
var object_1:Point = new Point(57,84);
var object_2:Point = new Point(500,86);
var object_3:Point = new Point(46,168);
var object_4:Point = new Point(479,126);
var object_5:Point = new Point(69,159);
var object_6:Point = new Point(443,162);
var object_7:Point = new Point(248,316);
var object_8:Point = new Point(209,198);
var object_9:Point = new Point(163,357);
var object_10:Point = new Point(440,283);
//constructor
public function KikkerOgen()
{
addEventListener(Event.ENTER_FRAME, Update);
addEventListener(MouseEvent.CLICK, isClicked);
timer.addEventListener(TimerEvent.TIMER, Knipperen);
timer.start();
gotoAndStop(13);
}
public function Update (event:Event)
{
trace(currentFrame);
}
//Score moet bij deze functie omhoog - document class
public function isClicked (event:MouseEvent):void
{
this.parent.removeChild(this);
}
//Hier telt hij het aantal keren dat de kikker moet knipperen
function Knipperen (event:TimerEvent):void
{
if (event.currentTarget.currentCount >= 2 && geknipperd < 3) {
geknipperd ++;
gotoAndPlay(1);
}
//Wanneer de kikker 3x geknipperd heeft moet hij naar een nieuwe positie
if (geknipperd == 3)
{
//Selecteer een random positie om heen te zwemmen
switch(Math.round(Math.random() * 10))
{
case 1:
x = object_1.x;
y = object_1.y;
break;
case 2:
x = object_2.x;
y = object_2.y;
break;
case 3:
x = object_3.x;
y = object_3.y;
break;
case 4:
x = object_4.x;
y = object_4.y;
break;
case 5:
x = object_5.x;
y = object_5.y;
break;
case 6:
x = object_6.x;
y = object_6.y;
break;
case 7:
x = object_7.x;
y = object_7.y;
break;
case 8:
x = object_8.x;
y = object_8.y;
break;
case 9:
x = object_9.x;
y = object_9.y;
break;
case 10:
x = object_10.x;
y = object_10.y;
break;
}
trace("posX:"+x);
trace("posY:"+y);
//Reset de timmer, het knipperen en laat hem opnieuw tellen om te verplaatsen.
geknipperd = 0;
trace(geknipperd);
//Tel hoevaak het kikkertje verplaatst is om de kikker bij 3x van stage te verwijderen.
if (aantalGezwommen < 3) {
aantalGezwommen++;
}
timer.reset();
timer.start();
}
}
//Wanneer de kikker 3x is verplaats verwijder hem uit het spel
function removeKikker ()
{
if (aantalGezwommen == 3)
{
this.parent.removeChild(this);
}
}
}
}
Apologies for the Dutch notes, things I need to remember :)
Nowhere in your code you are calling the removeKikker function. For a function to run it has to be called.

Game speeds up after restart

So I have this whole bunch of flash, actionscript3 code that works as a flappybird/shooting game.
The problem is I made a restart button at the very bottom of the code but everytime I click the restart button the game speeds itself up.
so all the Pipes I made move twice as fast and so on.
this will happen everytime restart the game with the restart button.
Sorry for the really long code, it's for school and thought maybe one of you guys could help me out why it keeps going faster everytime I hit de afbutton.
Don't mind the comments By the way, it's in dutch.
Here is the code
package
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class algemeClass extends MovieClip
{
//Hier maak ik alle variablen aan.
var speed:Number;
var fishVel:Number = 0;
var Gravity:Number = 0.75;
var score:int = 0;
var bestscore:int = 0;
//Hier alle Booleans
var End:Boolean = false;
var Pause:Boolean = true;
//Hier alles voor addChild.
var Fish = new myFish ();
var Pipe = new pipe ();
var Pipe1 = new pipe ();
var Pipe2 = new pipe ();
var Pipe3 = new pipe ();
var Pipe4 = new pipe ();
var Pipe5 = new pipe ();
var Pipe6 = new pipe ();
var Pipe7 = new pipe ();
var bubble1 = new bubble ();
var bubble2 = new bubble ();
var bubble3 = new bubble ();
var bubble4 = new bubble();
var haaienLijn = new haaienlijn ();
var scorelijn = new scoreLijn ();
public var afbutton = new afButton ();
//Hier mijn array voor het schieten van de bullets.
var Bullets:Array = new Array ();
var Bullets2:Array = new Array();
var Bullets3:Array = new Array ();
var Bullets4:Array = new Array ();
var Enemies:Array = new Array ();
//Hier komen alle Timers
var AddEnemyTimer:Timer = new Timer(3000);
//Hier alle Numbers/Integres.
public var startbutton =new startButton();
//Variable met random getal
var random1:int = Math.random() * 15;
var random2:int = Math.random() * 15;
var random3:int = Math.random() * 15;
var random4:int = Math.random() * 15;
//CONSTRUCTOR
/*Dit wordt meteen afgespeeld als het spel gestart wordt.
Ik wou hier graag dat er een start knop komt waarna het spel begint */
public function algemeClass()
{
//Hier wordt een startknop aangemaakt.
addChild(startbutton);
//Hier wordt de positie van de startknop bepaalt.
startbutton.x = 275;
startbutton.y = 200;
//Hier voeg ik een eventlistener toe om te luisteren wanneer er op de startbutton wordt geklikt
addEventListener(MouseEvent.CLICK,startGame);
//Dit is de functie voor de hierboven genoemde listener.
function startGame(event:MouseEvent)
{
//als deze functie wordt uitgevoerd. zullen de volgende dingen gebeuren.
//het spel de game wordt gestart.
theGames();
//De eventlistener die naar de startknop luisterd wordt verwijderd
removeEventListener(MouseEvent.CLICK,startGame);
//hier wordt de startknop van de stage verwijdert
if (startbutton.parent)
{
startbutton.parent.removeChild(startbutton);
}
}
}
//DE HEADFUNCTION
function theGames()
{
//EVERY ADDCHILDS
addChild(Pipe);
addChild(Pipe1);
addChild(Pipe2);
addChild(Pipe3);
addChild(Pipe4);
addChild(Pipe5);
addChild(Pipe6);
addChild(Pipe7);
addChild(scorelijn);
addChild(bubble1);
addChild(bubble2);
addChild(bubble3);
addChild(bubble4);
addChild(Fish);
addChild(haaienLijn);
//EVERY POSITION
//Dit is de eerste pijp en die begint buiten het scherm.
Pipe.x = 550;
/*De Y van deze pijp wordt bepaalt door een random getal.
Dit getal wordt bepaalt door de maximale Y positie te nemen die pijp mag zijn
en er dan een random getal tussen 0 en 10*245 bij op te tellen.
Zo kunnen de pijpen van bijna helemaal boven naar bijna helemaal onderaan gaan.*/
Pipe.y = (330 - (Math.floor(Math.random()*330)));
/* hier wordt gezegd dat de tegenhanger van pijp een waar je tussendoormoet dezelfde
Y als pijp 1 heeft alleen dan -800 waardoor het gat ontstaat*/
Pipe1.y = Pipe.y + 800;
//Zie voor pijp en pijp1
Pipe2.y = (330 - (Math.floor(Math.random()*330)));
Pipe2.x = Pipe.x + 250;
//Zie voor pijp en pijp1
Pipe3.y = Pipe2.y + 800;
//Zie voor pijp en pijp1
Pipe4.y = (330 - (Math.floor(Math.random()*330)));
Pipe4.x = Pipe.x + 500;
//Zie voor pijp en pijp1
Pipe5.y = Pipe4.y + 800;
//Zie voor pijp en pijp1
Pipe6.y = (330 - (Math.floor(Math.random()*330)));
Pipe6.x = Pipe.x + 750;
//Zie voor pijp en pijp1
Pipe7.y = Pipe6.y + 800;
/* dit is de scorelijn waar je een punt krijgt als je erdoorheen vliegt
deze heeft een standaar X en Y positie alleen beweegt wel*/
scorelijn.y = 200;
scorelijn.x = 550;
bubble1.x = Math.random() * 550;
bubble1.y = 620;
//Zie bubble1
bubble2.x = Math.random() * 550;
bubble2.y = 620;
//Zie bubble1
bubble3.x = Math.random() * 550;
bubble3.y = 620;
//Zie bubble1
bubble4.x = Math.random() * 550;
bubble4.y = 620;
//startpositie van de vis
Fish.x = 200;
Fish.y = 200;
haaienLijn.x = -50;
haaienLijn.y = 300;
score_txt.text = score.toString();
afbutton.x = 275;
afbutton.y = 200;
//EVERY EVENTLISTENER
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler3);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler4);
stage.addEventListener(MouseEvent.MOUSE_DOWN,fishSwim);
addEventListener(Event.ENTER_FRAME,Main);
AddEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy);
afbutton.addEventListener(MouseEvent.CLICK,onAfButton);
//THE MAIN FUNCTIE
function Main(event:Event):void
{
bubbleMove();
pipeMove();
scoreSchrijf();
Oneindig();
Jump();
Shooting();
Shooting2();
Shooting3();
Shooting4();
moveEnemies();
checkCollisions();
checkCollisions2();
checkCollisions3();
checkCollisions4();
checkCollisions5();
checkCollisions6();
Af();
}
//FUNCTION BUBBLEMOVE
//In dit gedeelte zal alles van de bubbles bepaalt worden.
function bubbleMove():void
{
/* De Y posities van de bubbles worden bepaalt door eerst te zeggen welke y de bubbles hebben
hierna zeg ik dat de nieuwe Y van de bubbles moet worden bepaalt door de hele tijd het random
gegenereerde getal van hierboven er van aftehalen waardoor de bubbel naar boven gaat*/
bubble1.y = bubble1.y - random1;
bubble2.y = bubble2.y - random2;
bubble3.y = bubble3.y - random3;
bubble4.y = bubble4.y - random4;
/*In dit stuk code wordt gezegd dat als de bubbel boven het scherm komt hij een nieuwe Y snelheid
zoals hier boven onderaan het scherm wordt geplaatst en een nieuwe random X Positie*/
if (bubble1.y < 0)
{
bubble1.x = Math.random() * 550;
bubble1.y = 620;
}
if (bubble2.y < 0)
{
bubble2.x = Math.random() * 550;
bubble2.y = 620;
}
if (bubble3.y < 0)
{
bubble3.x = Math.random() * 550;
bubble3.y = 620;
}
if (bubble4.y < 0)
{
bubble4.x = Math.random() * 550;
bubble4.y = 620;
}
}
//FUNCTION PIPEMOVE
/* bij deze eventlistener zullen alle pijpen en scorelijnen gaan bewegen*/
function pipeMove():void
{
//De standaard snelheid van alle onderdelen is -4
Pipe.x = Pipe.x - 4;
//alle tegenhangende pijpen krijgen de zelfde X als de tegenhanger.
Pipe1.x = Pipe.x;
Pipe2.x = Pipe2.x - 4;
Pipe3.x = Pipe2.x;
Pipe4.x = Pipe4.x - 4;
Pipe5.x = Pipe4.x;
Pipe6.x = Pipe6.x - 4;
Pipe7.x = Pipe6.x;
scorelijn.x = scorelijn.x - 4;
}
//FUNCTION SCORESCHIJF
//Hier zal worden bepaalt of er sprake is van een score
function scoreSchrijf():void
{
/* Hier wordt gezegd dat als de vis met object in aanraking komt er +1 bij de score moet komen
nadat dat is gebeurt moet de X van de lijn naar 275 naar links gaan
DIt getal 275 is het getal tussen de buizen. Dus elke keer als je door de lijn gaat
zal de lijn naar de volgende buis gaan en kun je hier ook scoren.*/
if (Fish.hitTestObject(scorelijn))
{
score = score + 1;
scorelijn.x = scorelijn.x + 250;
}
//Hier wordt de score omgezet voor het textvak en daar weergegeven
score_txt.text = score.toString();
}
//FUNCTION PIJPEN BLIJVEN GAAN
//Deze wordt toegevoegd om ervoor te zorgen dat alles door blijft gaan.
function Oneindig():void
{
/*er wordt hier gezegd dat als de pijp buiten het scherm verdwijnt hij weer een nieuwe
random Y positie moet krijgen en dat de tegenhangende pijp weer het gat moet maken.
De X positie van de buis wordt bepaalt door hem +275 achter de laatste buis te plaatsen
hierdoor zal hij de hele tijd terugkomen aangezien dit met elke buis gebeurd.
dus als buis 0/1 buiten het scherm gaan komen ze 275 achter 6/7
als 2/3 buiten het scherm komt komt hij achter de pijp 0/1, ze komen dan dus de hele tijd
achter hun voorganger aan.*/
if (Pipe.x <= -100)
{
Pipe.y = (330 - (Math.floor(Math.random()*330)));
Pipe.x = Pipe6.x + 250;
Pipe1.y = Pipe.y + 800;
}
if (Pipe2.x <= -100)
{
Pipe2.y = (330 - (Math.floor(Math.random()*330)));
Pipe2.x = Pipe.x + 250;
Pipe3.y = Pipe2.y + 800;
}
if (Pipe4.x <= -100)
{
Pipe4.y = (330 - (Math.floor(Math.random()*330)));
Pipe4.x = Pipe2.x + 250;
Pipe5.y = Pipe4.y + 800;
}
if (Pipe6.x <= -100)
{
Pipe6.y = (330 - (Math.floor(Math.random()*330)));
Pipe6.x = Pipe4.x + 250;
Pipe7.y = Pipe6.y + 800;
}
}
//FUNCTION JUMPEN
//hier wordt de gravity voor de vis bepaalt
function Jump():void
{
//hier wordt gezegd dat de Y van de vis de hele tijd + fishVel (fishvelocity) gaat en dit is eerst 0
Fish.y = Fish.y + fishVel;
/* hier wordt de fishvel bepaald door de hele tijd gravity erbij op te tellen dus hij stal steeds
sneller naar beneden gaan vallen*/
fishVel = fishVel + Gravity;
}
//Als je klikt maak je de Fishvel -11 waarna hij steeds weer -8 gaat doen. hij schiet dus heel even omhoog
//FUNCTION GRAVITY VAN DE VIS
function fishSwim(event:MouseEvent):void
{
fishVel = -11;
}
//FUNCTION VOOR HET REAGEREN OP SCHIETEN
//Hier registreert hij of je het knopje wat ik aangeef inklikt
function keyDownHandler(keyEvent:KeyboardEvent):void
{
//keyCode geeft aan om welk knopje het gaat
if (keyEvent.keyCode == 68)
{
//Dus als je het knopje van die functie indrukt gebeurt de functie shootbullet
shootBullet();
}
}
//FUNCTION VOOR HET MAKEN VAN SCHIETEN
//dit is de functie shootbullet
function shootBullet():void
{
//eerst maak je nieuwe bullets in de array aan
var Bullet:bullet = new bullet();
//daarna zeg ik dat de start positie van de bullet hetzelfde als de vis moet zijn
Bullet.x = Fish.x + 25;
Bullet.y = Fish.y;
//Hier wordt een bullet aan de stage toegevoegd
addChild(Bullet);
//en hier drukt hij de vorige bullet verder in de array
Bullets.push(Bullet);
}
//FUNCTION VOOR DOEN VAN HET SCHIETEN
function Shooting():void
{
/* hier gebruik ik een for loop om te bepalen dat wanneer b kleiner is dan de arrays length
de loop wil blijven gaan.
bij de b maak je gewoon een variable aan.
de hele tijd moet hij b++ omdat door de array heen, zodat je de hele tijd door de bullets
in de array kan komen */
for (var b:int = 0; b < Bullets.length; b++)
{
//dit is de functie voor het bewegen van de bullet
Bullets[b].x += 10;
//hier wordt gezegd dat als de bullet buiten de stage komt hij moet worden verwijderd
if (Bullets[b].x > stage.stageWidth)
{
removeChild(Bullets[b]);
Bullets[b] = null;
Bullets.splice(b,1);
}
}
}
//FUNCTION VOOR HET REAGEREN OP SCHIETEN2
/* ALLE COMMENTS IN DE FUNCTIE HIERBOVEN VAN HET HELE SCHIETEN GELDEN OOK VOOR DE 3 FUNCTIE HIERONDER*/
function keyDownHandler2(keyEvent2:KeyboardEvent):void
{
if (keyEvent2.keyCode == 65)
{
shootBullet2();
}
}
//FCUNTION VOOR HET MAKEN VAN SCHIETEN2
function shootBullet2():void
{
var Bullet:bullet = new bullet();
Bullet.x = Fish.x + 25;
Bullet.y = Fish.y;
addChild(Bullet);
Bullets2.push(Bullet);
}
//FUNCTION VOOR HET DOEN VAN SCHIETEN2
function Shooting2():void
{
for (var b:int = 0; b < Bullets2.length; b++)
{
Bullets2[b].x -= 10;
if (Bullets2[b].x > stage.stageWidth)
{
removeChild(Bullets2[b]);
Bullets2[b] = null;
Bullets2.splice(b,1);
}
}
}
//FCUNTION VOOR HET REAGEREN VAN SCHIETEN3
function keyDownHandler3(keyEvent3:KeyboardEvent):void
{
if (keyEvent3.keyCode == 87)
{
shootBullet3();
}
}
//FUNCTION VOOR HET MAKEN VAN SCHIETEN3
function shootBullet3():void
{
var Bullet:bullet = new bullet ();
Bullet.x = Fish.x + 25;
Bullet.y = Fish.y;
addChild(Bullet);
Bullets3.push(Bullet);
}
//FCUNTION VOOR HET DOEN VAN SCHIETEN3
function Shooting3():void
{
for (var b:int = 0; b < Bullets3.length; b++)
{
Bullets3[b].y -= 10;
if (Bullets3[b].Y > stage.stageHeight)
{
removeChild(Bullets3[b]);
Bullets3[b] = null;
Bullets3.splice(b,1);
}
}
}
//FCUNTION VOOR HET REAGEREN VAN SCHIETEN4
function keyDownHandler4(keyEvent4:KeyboardEvent):void
{
if (keyEvent4.keyCode == 83)
{
shootBullet4();
}
}
//FCUNTION VOOR HET MAKEN VAN SCHIETEN4
function shootBullet4():void
{
var Bullet:bullet = new bullet();
Bullet.x = Fish.x + 25;
Bullet.y = Fish.y;
addChild(Bullet);
Bullets4.push(Bullet);
}
//FUNCTION VOOR HET DOEN VAN SCHIETEN4
function Shooting4():void
{
for (var b:int = 0; b < Bullets4.length; b++)
{
Bullets4[b].y += 10;
if (Bullets4[b].x > stage.stageWidth)
{
removeChild(Bullets4[b]);
Bullets4[b] = null;
Bullets4.splice(b,1);
}
}
}
//hier laat ik de timer starten;
AddEnemyTimer.start();
//FUNCITON VOOR HET SPAWNEN VAN ENEMIES
//deze functie zorgt ervoor dat er enemys spawnen;
function addEnemy(event:TimerEvent):void
{
//Dit zorgt ervoor dat er nieuwe enemies aan de array worden toegevoegd
var monster:Enemy = new Enemy();
//hier wordt de startwaarde van de enemies bepaald
monster.x = stage.stageWidth + 200;
monster.y = (500 - (Math.floor(Math.random()*400)));
//hier wordt de enemy toegevoegd
addChild(monster);
//en hier wordt hij door geduwd in de array
Enemies.push(monster);
}
//FUNCTION VOOR HET BEWEGEN VAN ENEMIES
function moveEnemies():void
{
for (var a:int = 0; a < Enemies.length; a++)
{
Enemies[a].x -= 2;
if (Enemies[a].x < -50)
{
removeChild(Enemies[a]);
Enemies[a] = null;
Enemies.splice(a,1);
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkCollisions():void
{
for (var b = Bullets.length -1; b >= 0; b--)
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Bullets[b].hitTestObject(Enemies[a]))
{
removeChild(Bullets[b]);
Bullets[b] = null;
Bullets.splice(b,1);
removeChild(Enemies[a]);
Enemies[a] = null;
Enemies.splice(a,1);
score = score + 5;
break;
}
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkCollisions2():void
{
for (var b = Bullets2.length -1; b >= 0; b--)
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Bullets2[b].hitTestObject(Enemies[a]))
{
removeChild(Bullets2[b]);
Bullets2[b] = null;
Bullets2.splice(b,1);
removeChild(Enemies[a]);
Enemies[a] = null;
Enemies.splice(a,1);
score = score + 5;
break;
}
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkCollisions3():void
{
for (var b = Bullets3.length -1; b >= 0; b--)
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Bullets3[b].hitTestObject(Enemies[a]))
{
removeChild(Bullets3[b]);
Bullets3[b] = null;
Bullets3.splice(b,1);
removeChild(Enemies[a]);
Enemies[a] = null;
Enemies.splice(a,1);
score = score + 5;
break;
}
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkCollisions4():void
{
for (var b = Bullets4.length -1; b >= 0; b--)
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Bullets4[b].hitTestObject(Enemies[a]))
{
removeChild(Bullets4[b]);
Bullets4[b] = null;
Bullets4.splice(b,1);
removeChild(Enemies[a]);
Enemies[a] = null;
Enemies.splice(a,1);
score = score + 5;
break;
}
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkCollisions5():void
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Enemies[a].hitTestObject(Fish))
{
clearing();
addChild(afbutton);
}
}
}
//FUNCTION VOOR HET CHECKEN VAN COLLISION TUSSEN BULLET EN ENEMY
function checkcollisions6():void
{
for (var a = Enemies.length -1; a >= 0; a--)
{
if (Enemies[a].hitTestObject(haaienLijn))
{
clearing();
addChild(afbutton);
}
}
}
//FUNCTION VOOR WANNEER JE AF BENT
function Af():void
{
if (Fish.y < 0)
{
clearing();
}
if (Fish.y > 600)
{
clearing();
}
if (Fish.hitTestObject(Pipe))
{
clearing();
}
if (Fish.hitTestObject(Pipe1))
{
clearing();
}
if (Fish.hitTestObject(Pipe2))
{
clearing();
}
if (Fish.hitTestObject(Pipe3))
{
clearing();
}
if (Fish.hitTestObject(Pipe4))
{
clearing();
}
if (Fish.hitTestObject(Pipe5))
{
clearing();
}
if (Fish.hitTestObject(Pipe6))
{
clearing();
}
if (Fish.hitTestObject(Pipe7))
{
clearing();
}
}
//FUNCITON DIE ALLE EVENTLISTENERS VERWIJDERT
function clearing():void
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler3);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler4);
stage.removeEventListener(MouseEvent.MOUSE_DOWN,fishSwim);
removeEventListener(Event.ENTER_FRAME,Main);
AddEnemyTimer.stop();
AddEnemyTimer.reset();
AddEnemyTimer.removeEventListener(TimerEvent.TIMER, addEnemy);
addChild(afbutton);
}
//FUNCTION VOOR HET KLIKKEN OP DE RESTART KNOP
function onAfButton(event:MouseEvent)
{
if (afbutton.parent)
{
afbutton.parent.removeChild(afbutton);
removeEventListener(MouseEvent.CLICK,onAfButton);
}
theGames();
if (score > bestscore)
{
bestscore = score;
}
highscore_txt.text = "Highscore : " + bestscore.toString();
score = 0;
}
}
}
}
I'm not sure how much help this will be as I work with Javascript and not Actionscript but I can almost guarantee you that the issue is being caused by the timer you have for the enemies. I would make sure you are removing the timer properly upon restarting.
I am assuming the af() function resets the game when your character hits a pipe etc.
It appears that your onAFButton function isn't actually resetting anything - it just calls theGames() to rebuild the game!
As a result, you tell all your items to set their speeds again, which will be double before.

AS3: Reset variables and repeat part of function

This is a class of my schoolproject but it doesn't work right now. http://pastebin.com/0K9H6wAi
I have a frog who blinks 3 times and than moves - so far, so good.
But when it has moves it has to blink again and move again, and i cant figure this out. This happens in line 109 till the end.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class KikkerOgen extends MovieClip {
var timer:Timer = new Timer(1000, 4);
var geknipperd:int = 0;
var hoevaakKnipperen:int = 0;
var aantalGezwommen
var score:int = 0;
//boompjes en bosjes
var object_1:Point = new Point(57,84);
var object_2:Point = new Point(500,86);
var object_3:Point = new Point(46,168);
var object_4:Point = new Point(479,126);
var object_5:Point = new Point(69,159);
var object_6:Point = new Point(443,162);
var object_7:Point = new Point(248,316);
var object_8:Point = new Point(209,198);
var object_9:Point = new Point(163,357);
var object_10:Point = new Point(440,283);
//constructor
public function KikkerOgen()
{
addEventListener(Event.ENTER_FRAME, Update);
addEventListener(MouseEvent.CLICK, isClicked);
timer.addEventListener(TimerEvent.TIMER, Knipperen);
timer.start();
gotoAndStop(13);
}
public function Update (event:Event)
{
trace(currentFrame);
}
//Score moet bij deze functie omhoog - document class
public function isClicked (event:MouseEvent):void
{
this.parent.removeChild(this);
}
//Hier telt hij het aantal keren dat de kikker moet knipperen
function Knipperen (event:TimerEvent):void
{
if (event.currentTarget.currentCount >= 2 && geknipperd < 3) {
geknipperd ++;
gotoAndPlay(1);
}
//Wanneer de kikker 3x geknipperd heeft moet hij naar een nieuwe positie
if (geknipperd == 3)
{
//Selecteer een random positie om heen te zwemmen
switch(Math.round(Math.random() * 10))
{
case 1:
x = object_1.x;
y = object_1.y;
break;
case 2:
x = object_2.x;
y = object_2.y;
break;
case 3:
x = object_3.x;
y = object_3.y;
break;
case 4:
x = object_4.x;
y = object_4.y;
break;
case 5:
x = object_5.x;
y = object_5.y;
break;
case 6:
x = object_6.x;
y = object_6.y;
break;
case 7:
x = object_7.x;
y = object_7.y;
break;
case 8:
x = object_8.x;
y = object_8.y;
break;
case 9:
x = object_9.x;
y = object_9.y;
break;
case 10:
x = object_10.x;
y = object_10.y;
break;
}
trace("posX:"+x);
trace("posY:"+y);
//Reset de timmer, het knipperen en laat hem opnieuw tellen om te verplaatsen.
geknipperd = 0;
trace(geknipperd);
timer.reset();
aantalGezwommen ++;
}
}
//Wanneer de kikker 3x is verplaats verwijder hem uit het spel
function removeKikker ()
{
if (aantalGezwommen == 3)
{
this.parent.removeChild(this);
}
}
}
}
Any idea what goes wrong here?
You call timer.reset(); which stops the timer but doesn't start it again.
Stops the timer, if it is running, and sets the currentCount property back to 0, like the reset button of a stopwatch.
Timer # AS3 reference
After you reset the timer, be sure to start it again with timer.start();