How to set a timer in JavaScript?

Started by
9 comments, last by Patriarch K 11 years, 1 month ago

This is not just about the timer. I wonder why it runs slow (at least on my computer). I've finally made my first JavaScript-game but I have some problems with the time. It works different on different machines. On my computer it goes very slow, but on my friends computer it goes fast as the light. When I increase the setTimeout to 100, then it goes very smooth on MY computer but then it lags on my friends computer. When I turn it to 30 it lags on MY computer but runs smooth on my friends computer.

What can be the problem? If you try my game you will probably see what it is about (key arrows and shoot with W)

http://www.yffisch.com/Rymd/index.html

Maybe you don't have anything to compare it with, but how am I supposed to set the "ground timer"? I haven't defined it.

Here is the source. It's very messy at the moment because I try to learn JavaScript:




var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');

var jet1 = new Jet();
var star1x = 0;
var star1y = 0;
var star1dx = -1;
var star1dy = 0;
var star2x = 0;
var star2y = 0;
var star2dx = -.5;
var star2dy = 0;
var star3x = 0;
var star3y = 0;
var star3dx = -.1;
var star3dy = 0;
var kills = 0;
var bossLife = 10;
var bossX = 200;
var bossY = 200;
var bossDX = 1;
var bossDY = 1;
var countdown = 15000;
var earthX = 800;
var earthY = 200;

var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        window.oRequestAnimationFrame;
var die = new Audio("images/eldljud.wav");
var hit = new Audio("images/Pop.wav");
var shoot = new Audio("images/eldljud.wav");
var music = new Audio("images/rymd2.mp3");
music.loop = true;
music.play();


var background = new Image();
background.src = 'images/background.png';
background.addEventListener('load', init, false);

var plane = new Image();
plane.src = 'images/PlaneLeft.gif';
plane.addEventListener('load', init, false);

var plane2 = new Image();
plane2.src = 'images/PlaneRight.gif';
plane2.addEventListener('load', init, false);

var bullet = new Image();
bullet.src = 'images/Bullet.gif';
bullet.addEventListener('load', init, false);

var star1 = new Image();
star1.src = 'images/background3c.png';
star1.addEventListener('load', init, false);

var star2 = new Image();
star2.src = 'images/background3b.png';
star2.addEventListener('load', init, false);

var star3 = new Image();
star3.src = 'images/background3a.png';
star3.addEventListener('load', init, false);

var star1b = new Image();
star1b.src = 'images/background4c.png';
star1b.addEventListener('load', init, false);

var star2b = new Image();
star2b.src = 'images/background4b.png';
star2b.addEventListener('load', init, false);

var star3b = new Image();
star3b.src = 'images/background4a.png';
star3b.addEventListener('load', init, false);

var enemy1 = new Image();
enemy1.src = 'images/enemy.gif';
enemy1.addEventListener('load', init, false);

var enemy2 = new Image();
enemy2.src = 'images/enemy2.gif';
enemy2.addEventListener('load', init, false);

var enemy3 = new Image();
enemy3.src = 'images/enemy3.gif';
enemy3.addEventListener('load', init, false);

var boss = new Image();
boss.src = 'images/boss.gif';
boss.addEventListener('load', init, false);

var earth = new Image();
earth.src = 'images/earth.png';
earth.addEventListener('load', init, false);

// main functions
function init() {
     
    loop();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
}

function loop() { 
     updateGame(); 
      setTimeout(loop,100); 
}

function updateGame(){

 ctxBg.drawImage(background, 0, 0);
       
      if(kills >= 20 && bossLife > 0){
         ctxBg.drawImage(boss, bossX, bossY);
     }
if(countdown > 0){
countdown--;
}

if(countdown <= 5000){
    ctxBg.drawImage(earth, earthX, earthY);
    if(countdown > 0){
    earthX -= 0.1;
}
}
        jet1.draw();
        jet1.move();
        jet1.spawnEnemy();
        jet1.collision();
        drawStars();
        
        if(countdown > 0){
        
        moveStar1();
        moveStar2();
        moveStar3();
       
        moveBoss();

        if(countdown <= 0){
            alert("YOU LOST! ENEMY INVADED EARTH!!");
        }
        if(bossLife <= 0){
            alert("YOU SAVED THE EARTH FROM THE EVIL SPAWN! CONGRATULATIONS!");
        }
    }
     drawText();
       // requestAnimFrame(loop);  

   
}

function drawStars(){
    if(countdown > 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 
}
if(countdown <= 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1b, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1b, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1b, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2b, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2b, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2b, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3b, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3b, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3b, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 
}
}


function moveStar1(){
star1x += star1dx;
}

function moveStar2(){
star2x += star2dx;
}

function moveStar3(){
star3x += star3dx;
}

function moveBoss(){
    bossX += bossDX;
    bossY += bossDY;

if(bossX <= 0 || bossX >= 750){
    bossDX *= -1;
}
if(bossY <= 0 || bossY >= 550){
    bossDY *= -1;
}

}


function drawText(){
ctxBg.lineWidth=1;
ctxBg.fillStyle="#FFFFFF";
ctxBg.lineStyle="#ffff00";
ctxBg.font="18px sans-serif";
ctxBg.fillText("Power: " + kills, 20, 20);
ctxBg.fillText(countdown + " km to earth", 650, 20);
}


function clearCtxBg() {
    ctxBg.clearRect(0, 0, 800, 600);
}

// end of main functions
// jet functions
function Jet() {
   
    this.drawX = 420;
    this.drawY = 200;
    this.dx = 0;
    this.dy = 0;
    this.direction = 1;
    this.fire = false;
    this.isShooting = false;
    this.bullets = [];
    this.currentBullet = 0;
    this.counter = 0;
    this.enemyRand;
    this.enemyRand2;

    this.enemies = [];
    this.currentEnemy = 0;
    for (var i = 0; i < 525; i++) {
        this.bullets[this.bullets.length] = new Bullet();
    }
     for (var i = 0; i < 125; i++) {
        this.enemies[this.enemies.length] = new Enemy();
    }
}

Jet.prototype.move = function(){
    this.drawX += this.dx;
    this.drawY += this.dy;
}

Jet.prototype.draw = function() {
    clearCtxJet();
    this.fireBullet();
    this.drawAllBullets();
    this.drawAllEnemies();
    if(jet1.direction == -1){
    ctxJet.drawImage(plane, this.drawX, this.drawY);
}
   if(jet1.direction == 1){
    ctxJet.drawImage(plane2, this.drawX, this.drawY);
}
}

Jet.prototype.drawAllBullets = function() {
    for (var i = 0; i < this.bullets.length; i++) {
        if (this.bullets[i].drawX >= 0 && this.bullets[i].bulletLife > 0) {
            this.bullets[i].draw();
            this.bullets[i].move();
           
        
       
        }
    }    
}

Jet.prototype.collision = function() {
   
 for (var i = 0; i < this.bullets.length; i++) {
    for (var j = 0; j < this.enemies.length; j++) {
    // Skjuta på bossen
    if(kills >= 20){    
if(this.bullets[i].drawX > bossX && this.bullets[i].drawX < bossX+100 && this.bullets[i].drawY > bossY && this.bullets[i].drawY < bossY+90 && this.bullets[i].bulletLife > 0 && bossLife > 0){
    bossLife--;
    this.bullets[i].bulletLife--;
}
}

        // Minuspoäng när fiender är utanför skärmen
            if(this.enemies[j].drawX > -10 && this.enemies[j].drawX < 0 && this.enemies[j].outScreen == false){
kills--;
this.enemies[j].outScreen = true;
            }
// Om en bullet krockar med en fiende
            if(this.bullets[i].drawX > this.enemies[j].drawX && this.bullets[i].drawX < this.enemies[j].drawX+50 && this.bullets[i].drawY+30 > this.enemies[j].drawY && this.bullets[i].drawY < this.enemies[j].drawY+25 && this.bullets[i].bulletLife > 0 && this.enemies[j].life > 0 ){
                this.enemies[j].life--;
                if(this.enemies[j].life < 1){
                    kills++;
                }
                this.bullets[i].bulletLife--;
            }
        }
      } 
}


Jet.prototype.drawAllEnemies = function() {
    for (var i = 0; i < this.enemies.length; i++) {
        if (this.enemies[i].drawX >= 0) {
           if(this.enemies[i].life > 0){
            this.enemies[i].draw();
            this.enemies[i].move();
        }
        
       
        }
    }    
}

Jet.prototype.fireBullet = function() {
    if (this.fire == true && this.isShooting == false) {
        this.isShooting = true;
        if(this.bullets[this.currentBullet].bulletLife > 0){
            if(this.direction == 1){
        this.bullets[this.currentBullet].fire(this.drawX+95, this.drawY);
    }
         if(this.direction == -1){
        this.bullets[this.currentBullet].fire(this.drawX, this.drawY);
    }

shoot.play();
        this.bullets[this.currentBullet].isShot = true;
    }
        if(this.direction == 1){
            this.bullets[this.currentBullet].dx = 3;
        }
        if(this.direction == -1){
             this.bullets[this.currentBullet].dx = -3;
        }
        this.currentBullet++;
       
        if (this.currentBullet >= this.bullets.length) this.currentBullet = 0;
        
    } else if (this.fire == false) {
        this.isShooting = false;
    }  
}

Jet.prototype.spawnEnemy = function(){
    this.counter++;
    this.enemyRand = Math.floor((Math.random()*10000)+200);
    this.enemyRand2 = Math.floor((Math.random()*580)+1);
     if (this.counter >= this.enemyRand) {
        
        this.enemies[this.currentEnemy].fire(800, this.enemyRand2);
        this.currentEnemy++;
       
        if (this.currentEnemy >= this.enemies.length) {
            this.currentEnemy = 0;
        }
        this.counter = 0;
    }   
}


function clearCtxJet() {
    ctxJet.clearRect(0, 0, 800, 600);
    ctxBullet.clearRect(0, 0, 800, 600);
}

// end of jet functions
// bullet functions
function Bullet() {
    this.drawX = -20;
    this.drawY = 0;
    this.dx = 3;
    this.isShot = false;
    this.bulletLife = 1;

}

Bullet.prototype.move = function(){
this.drawX += this.dx;
}

Bullet.prototype.draw = function() {
   if( this.bulletLife > 0){
    ctxBullet.drawImage(bullet, this.drawX, this.drawY+25);
}
  
}

Bullet.prototype.fire = function(startX, startY) {
   
    this.drawX = startX;
    this.drawY = startY;
}

// end of bullet functions

// enemy functions
function Enemy() {
    this.drawX = -20;
    this.drawY = 0;
    this.dx;
    this.isShot = false;
    this.life = 3;
    this.outScreen = false;
}

Enemy.prototype.move = function(){
if(this.life == 3){
this.dx = 1;
}
if(this.life == 2){
this.dx = 2;
}
if(this.life == 1){
this.dx = 3;
}
this.drawX -= this.dx;
}

Enemy.prototype.draw = function() {
   
   if(this.life == 3){
    ctxBullet.drawImage(enemy1, this.drawX, this.drawY);
}
  if(this.life == 2){
    ctxBullet.drawImage(enemy2, this.drawX, this.drawY);
}
  if(this.life == 1){
    ctxBullet.drawImage(enemy3, this.drawX, this.drawY);
}


}

Enemy.prototype.fire = function(startX, startY) {
    this.drawX = startX;
    this.drawY = startY;
}

// end of enemy functions





// event functions

function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow
         jet1.dy = -1;    
    }
    if (keyID === 39 ) { //right arrow
      jet1.direction = 1;
        jet1.dx = 1;    
    }
    if (keyID === 40 ) { //down arrow 
        jet1.dy = 1;   

    }
    if (keyID === 37 ) { //left arrow 
          jet1.dx = -1; 
          jet1.direction = -1;
    }
    if (keyID === 87) { //spacebar
        jet1.fire = true;
       
    }
}

function checkKeyUp(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow 
     jet1.dy = 0; 
    }
    if (keyID === 39 ) { //right arrow 
      jet1.dx = 0; 
    }
    if (keyID === 40 ) { //down arrow 
      jet1.dy = 0; 
    }
    if (keyID === 37 ) { //left arrow 
      jet1.dx = 0; 
    }
    if (keyID === 87) { //spacebar
        jet1.fire = false;  
    }
}

// end of event functions

Advertisement

Why you dont use requestAnimationFrame ?

Your problem is that the setTimeout calls are stacked when they cant be processed fast enough

also they're pretty imprecise and have a relatively large overhead.

Also you could use a game engine, there are several 2D game engines available.

If you dont want to use an engine you should look at them anyway and check how their code is structured.

Jan F. Scheurer - CEO @ Xe-Development

Sign Up for Xe-Engine™Beta

Well, when I used the requestAnimationFrame it barely works at all. When I activate that then the game lags incredibly much. Even if I remove the setTimeout.

Do you have some kind of solution for me by using my existing code and not an engine? Can double buffering and that stuff have anything to do with this?

Well, I profiled your code using google chrome. If you don't know this feature this is an excellent time to learn it. It tells you where your code spends the most time. You use it by opening up the developer tools, clicking on the profiles tab, then select the javascript cpu profile. Run the profiler then go ahead and play your game normally. After a short time stop the profiler and it will show you where your code spends the most time. This is what I found

60.62% of the time your programming is running in the Jet.collision method. It seems you are doing collision on 525 bullets against 125 enemies. This is 65625 total checks. Speeding that up would give you the most benefits. Consider only updating the bullets or enemies on screen. That would greatly reduce the amount of work needed. But 65625 really isn't a very large number. It shouldn't be slowing down your game as much as I have seen.

I think the problem you are running into is that you are setting init to be the load callback for all of your images. That means every time an image is loaded, it calls init and init calls loop. You have 15 game loops running at the same time. Your set timeout interval is only 100, that means for a single game loop you have about 10 frames per second. You have 15 game loops so your game is trying to do 150 frames per second.

So to fix it. You should keep track of how many images you have to load, store that number somewhere. Have your images use a different callback function. This function should subtract one from your pending image count. If it reaches 0 then you call init.
var pendingImages = 15;

var plane2 = new Image();
plane2.src = 'images/PlaneRight.gif';
plane2.addEventListener('load', imageLoaded, false);

var bullet = new Image();
bullet.src = 'images/Bullet.gif';
bullet.addEventListener('load', imageLoaded, false);
...

function imageLoaded()
{
    --pendingImages;
    if (pendingImages == 0)
    {
        init();
    }
}
Once you add this your game will probably run slow because it will be running at 10 frames per second instead of trying to pull 150. So you will have to increase the velocity of all the objects on screen and change the timeout time to be less for a faster framerate. I would personally use just requestAnimationFrame.

EDIT:
Also, looking over your code I noticed that you are using three different rendering contexts. I would recommend only using one.
My current game project Platform RPG

Wow, thanks a lot HappyCoder! That really made everything!! That made me understand very much about kind of everything. Thanks!

I got a new "problem". It's a very small one but I can't really find out any solution to this. If you look at my code then you will see that when you've got 100 "kills" then a boss will be spawned. Though, when I spawn my boss the game start to lag pretty much. I don't really get why. There must be some leak somewhere, but I can't really locate it.

I tried that google thing and found out that the jet.collision took about 33%, but that should be no problem. It's something with the boss that I spawn which I can't really see.

Can you locate it?! I know that it is a bit messy to look at my code, but just search for the things with "boss" in it's name and you will see a couple of things.



var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');

var jet1 = new Jet();
var star1x = 0;
var star1y = 0;
var star1dx = -2.4;
var star1dy = 0;
var star2x = 0;
var star2y = 0;
var star2dx = -1.4;
var star2dy = 0;
var star3x = 0;
var star3y = 0;
var star3dx = -.4;
var star3dy = 0;
var kills = 0;
//var bossLife = 40;
var bossX = 200;
var bossY = 200;
var bossDX = 3;
var bossDY = 3;
var countdown = 15000;
var earthX = 800;
var earthY = 200;
var pendingImages = 16;
var difficulty = 100;
var shootCounter = 0;
var shootLimit = 34;

var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        window.oRequestAnimationFrame;
var die = new Audio("images/eldljud.wav");
var hit = new Audio("images/Pop.wav");
var shoot = new Audio("images/eldljud.wav");
var music = new Audio("images/rymd2.mp3");
music.loop = true;
music.play();


var background = new Image();
background.src = 'images/background.png';
background.addEventListener('load', imageLoaded, false);

var plane = new Image();
plane.src = 'images/PlaneLeft.gif';
plane.addEventListener('load', imageLoaded, false);

var plane2 = new Image();
plane2.src = 'images/PlaneRight.gif';
plane2.addEventListener('load', imageLoaded, false);

var bullet = new Image();
bullet.src = 'images/Bullet.gif';
bullet.addEventListener('load', imageLoaded, false);

var star1 = new Image();
star1.src = 'images/background3c.png';
star1.addEventListener('load', imageLoaded, false);

var star2 = new Image();
star2.src = 'images/background3b.png';
star2.addEventListener('load', imageLoaded, false);

var star3 = new Image();
star3.src = 'images/background3a.png';
star3.addEventListener('load', imageLoaded, false);

var star1b = new Image();
star1b.src = 'images/background4c.png';
star1b.addEventListener('load', imageLoaded, false);

var star2b = new Image();
star2b.src = 'images/background4b.png';
star2b.addEventListener('load', imageLoaded, false);

var star3b = new Image();
star3b.src = 'images/background4a.png';
star3b.addEventListener('load', imageLoaded, false);

var enemy1 = new Image();
enemy1.src = 'images/enemy.gif';
enemy1.addEventListener('load', imageLoaded, false);

var enemy2 = new Image();
enemy2.src = 'images/enemy2.gif';
enemy2.addEventListener('load', imageLoaded, false);

var enemy3 = new Image();
enemy3.src = 'images/enemy3.gif';
enemy3.addEventListener('load', imageLoaded, false);

var boss = new Image();
boss.src = 'images/boss.gif';
boss.addEventListener('load', imageLoaded, false);

var earth = new Image();
earth.src = 'images/earth.png';
earth.addEventListener('load', imageLoaded, false);

var sprite = new Image();
sprite.src = 'images/planeSprite.png';
sprite.addEventListener('load', imageLoaded, false);

// main functions
function init() {
    
    loop();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
}

function loop() { 
     updateGame();  
       requestAnimFrame(loop); 
}

function imageLoaded()
{
    --pendingImages;
    if (pendingImages == 0)
    {
        init();
    }
}

var spriteX = 0;
var spriteY = 0;
var spriteXstor = 100;
var spriteYstor = 55;
var changer = 1;
var lol = false;
var timerAnim = 0;

function redrawTest() {
  if(jet1.direction == 1){
     ctxBg.drawImage(sprite, spriteX, 0, spriteXstor, spriteYstor, jet1.drawX, jet1.drawY, spriteXstor, spriteYstor);
 }
  if(jet1.direction == -1){
     ctxBg.drawImage(sprite, spriteX, 55, spriteXstor, spriteYstor, jet1.drawX, jet1.drawY, spriteXstor, spriteYstor);
 }
}

function updateSprite(){
    redrawTest();
if(lol == false){
spriteX += 100;
if(spriteX >= 500 ){
    spriteX = 0;
}
lol = true;
} 
}

function updateGame(){

 ctxBg.drawImage(background, 0, 0);
     timerAnim++;
     shootCounter++;
     if(timerAnim == 5){
lol = false;
        timerAnim = 0;
     }  
      
if(countdown > 0){
countdown--;
}

if(countdown <= 5000){
    ctxBg.drawImage(earth, earthX, earthY);
    if(countdown > 0){
    earthX -= 0.1;
}
}
        jet1.draw();
        jet1.move();
        jet1.spawnEnemy();
        jet1.collision();
        drawStars();
        redrawTest();
        diffSet();
        if(countdown > 0){
        
        moveStar1();
        moveStar2();
        moveStar3();
       
        moveBoss();
updateSprite();
        if(countdown <= 0){
            alert("YOU LOST! ENEMY INVADED EARTH!!");
        }
        if(jet1.bossLife <= 0){
            alert("YOU SAVED THE EARTH FROM THE EVIL SPAWN! CONGRATULATIONS!");
        }
    }
     drawText();
       

   
}

function diffSet(){
    if(kills >= 5 && kills < 10){
difficulty = 95;
shootLimit = 30;
    }
    if(kills >= 10 && kills < 20){
    difficulty = 90;  
    shootLimit = 25;  
    }
    if(kills >= 20 && kills < 30){
     difficulty = 80; 
     shootLimit = 23;  
    }
    if(kills >= 30 && kills < 40){
     difficulty = 65;  
     shootLimit = 21; 
    }
    if(kills >= 40 && kills < 50){
     difficulty = 55; 
     shootLimit = 19;  
    }
    if(kills >= 50 && kills < 60){
      difficulty = 40; 
      shootLimit = 17; 
    }
    if(kills >= 60 && kills < 70){
      difficulty = 30; 
      shootLimit = 12; 
    }
    if(kills >= 70 && kills < 80){
       difficulty = 20; 
       shootLimit = 7;
    }
    if(kills >= 80 && kills < 90){
      difficulty = 10; 
      shootLimit = 3; 
    }
    if(kills >= 90 && kills < 100){
      difficulty = 8;  
      shootLimit = 1;
    }
}


function drawStars(){
    if(countdown > 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 
}
if(countdown <= 7500){
            // Först stjärnorna
                if(star1x > -1000){
                    ctxBg.drawImage(star1b, star1x, star1y);
                }
                if(star1x < 0){
                     ctxBg.drawImage(star1b, star1x+800, star1y);
                    if(star1x + 800 < 0){
                       ctxBg.drawImage(star1b, star1x+1600, star1y);
                        star1x = 0;
                    }
                }
             //////  
               // Andra stjärnorna
                if(star2x > -1000){
                    ctxBg.drawImage(star2b, star2x, star2y);
                }
                if(star2x < 0){
                     ctxBg.drawImage(star2b, star2x+800, star2y);
                    if(star2x + 800 < 0){
                       ctxBg.drawImage(star2b, star2x+1600, star2y);
                        star2x = 0;
                    }
                }
             ////// 
               // Tredje stjärnorna
                if(star3x > -1000){
                    ctxBg.drawImage(star3b, star3x, star3y);
                }
                if(star3x < 0){
                     ctxBg.drawImage(star3b, star3x+800, star3y);
                    if(star3x + 800 < 0){
                       ctxBg.drawImage(star3b, star3x+1600, star3y);
                        star3x = 0;
                    }
                }
             ////// 

}
 
}


function moveStar1(){
star1x += star1dx;
}

function moveStar2(){
star2x += star2dx;
}

function moveStar3(){
star3x += star3dx;
}

function moveBoss(){
    bossX += bossDX;
    bossY += bossDY;

if(bossX <= 0 || bossX >= 750){
    bossDX *= -1;
}
if(bossY <= 0 || bossY >= 550){
    bossDY *= -1;
}

if(kills >= 100 && jet1.bossLife > 0){
         ctxBg.drawImage(boss, bossX, bossY);
     }

}


function drawText(){
ctxBg.lineWidth=1;
ctxBg.fillStyle="#FFFFFF";
ctxBg.lineStyle="#ffff00";
ctxBg.font="18px sans-serif";
ctxBg.fillText("Power: " + kills, 20, 20);
ctxBg.fillText(countdown + " km to earth", 650, 20);
}


function clearCtxBg() {
    ctxBg.clearRect(0, 0, 800, 600);
}

// end of main functions
// jet functions
function Jet() {
   
    this.drawX = 420;
    this.drawY = 200;
    this.dx = 0;
    this.dy = 0;
    this.direction = 1;
    this.fire = false;
    this.isShooting = false;
    this.bullets = [];
    this.currentBullet = 0;
    this.counter = 0;
    this.enemyRand;
    this.enemyRand2;
    this.bossLife = 40;

    this.enemies = [];
    this.currentEnemy = 0;
    for (var i = 0; i < 800; i++) {
        this.bullets[this.bullets.length] = new Bullet();
    }
     for (var i = 0; i < 300; i++) {
        this.enemies[this.enemies.length] = new Enemy();
    }
}

Jet.prototype.move = function(){
    this.drawX += this.dx;
    this.drawY += this.dy;
}

Jet.prototype.draw = function() {
    clearCtxJet();
    this.fireBullet();
    this.drawAllBullets();
    this.drawAllEnemies();
   
}

Jet.prototype.drawAllBullets = function() {
    for (var i = 0; i < this.bullets.length; i++) {
        if (this.bullets[i].drawX >= 0 && this.bullets[i].bulletLife > 0) {
            this.bullets[i].draw();
            this.bullets[i].move();
           
        
       
        }
    }    
}

Jet.prototype.collision = function() {
   
 for (var i = 0; i < this.bullets.length; i++) {
    for (var j = 0; j < this.enemies.length; j++) {
    // Skjuta på bossen
    if(kills >= 100){    
if(this.bullets[i].drawX > bossX && this.bullets[i].drawX < bossX+100 && this.bullets[i].drawY > bossY && this.bullets[i].drawY < bossY+90 && this.bullets[i].bulletLife > 0 && this.bossLife > 0){
    
   this.bullets[i].bulletLife--;
   this.bossLife--;
}
}

        // Minuspoäng när fiender är utanför skärmen
            if(this.enemies[j].drawX > -10 && this.enemies[j].drawX < 0 && this.enemies[j].outScreen == false){
kills--;
this.enemies[j].outScreen = true;
            }
// Om en bullet krockar med en fiende
            if(this.bullets[i].drawX > this.enemies[j].drawX && this.bullets[i].drawX < this.enemies[j].drawX+50 && this.bullets[i].drawY+30 > this.enemies[j].drawY && this.bullets[i].drawY < this.enemies[j].drawY+25 && this.bullets[i].bulletLife > 0 && this.enemies[j].life > 0 ){
                this.enemies[j].life--;
                if(this.enemies[j].life < 1){
                    kills++;
                }
                this.bullets[i].bulletLife--;
            }
        }
      } 
}


Jet.prototype.drawAllEnemies = function() {
    for (var i = 0; i < this.enemies.length; i++) {
        if (this.enemies[i].drawX >= 0) {
           if(this.enemies[i].life > 0){
            this.enemies[i].draw();
            this.enemies[i].move();
        }
        
       
        }
    }    
}

Jet.prototype.fireBullet = function() {
    if (this.fire == true && this.isShooting == false) {
        this.isShooting = true;
        if(this.bullets[this.currentBullet].bulletLife > 0){
            if(this.direction == 1){
        this.bullets[this.currentBullet].fire(this.drawX+95, this.drawY);
    }
         if(this.direction == -1){
        this.bullets[this.currentBullet].fire(this.drawX, this.drawY);
    }

shoot.play();
        this.bullets[this.currentBullet].isShot = true;
    }
        if(this.direction == 1){
            this.bullets[this.currentBullet].dx = 8;
        }
        if(this.direction == -1){
             this.bullets[this.currentBullet].dx = -8;
        }
        this.currentBullet++;
       
        if (this.currentBullet >= this.bullets.length) this.currentBullet = 0;
        
    } else if (this.fire == false) {
        this.isShooting = false;
    }  
}

Jet.prototype.spawnEnemy = function(){
    this.counter++;
    this.enemyRand = Math.floor((Math.random()*500)+difficulty);
    this.enemyRand2 = Math.floor((Math.random()*550)+1);
     if (this.counter >= this.enemyRand) {
        
        this.enemies[this.currentEnemy].fire(800, this.enemyRand2);
        this.currentEnemy++;
       
        if (this.currentEnemy >= this.enemies.length) {
            this.currentEnemy = 0;
        }
        this.counter = 0;
    }   
}


function clearCtxJet() {
    ctxJet.clearRect(0, 0, 800, 600);
    ctxBullet.clearRect(0, 0, 800, 600);
}

// end of jet functions
// bullet functions
function Bullet() {
    this.drawX = -20;
    this.drawY = 0;
    this.dx = 3;
    this.isShot = false;
    this.bulletLife = 1;

}

Bullet.prototype.move = function(){
this.drawX += this.dx;
}

Bullet.prototype.draw = function() {
   if( this.bulletLife > 0){
    ctxBullet.drawImage(bullet, this.drawX, this.drawY+25);
}
  
}

Bullet.prototype.fire = function(startX, startY) {
   
    this.drawX = startX;
    this.drawY = startY;
}

// end of bullet functions

// enemy functions
function Enemy() {
    this.drawX = -20;
    this.drawY = 0;
    this.dx;
    this.isShot = false;
    this.life = 3;
    this.outScreen = false;
}

Enemy.prototype.move = function(){
if(this.life == 3){
this.dx = 2.5;
}
if(this.life == 2){
this.dx = 4.1;
}
if(this.life == 1){
this.dx = 6;
}
this.drawX -= this.dx;
}

Enemy.prototype.draw = function() {
   
   if(this.life == 3){
    ctxBullet.drawImage(enemy1, this.drawX, this.drawY);
}
  if(this.life == 2){
    ctxBullet.drawImage(enemy2, this.drawX, this.drawY);
}
  if(this.life == 1){
    ctxBullet.drawImage(enemy3, this.drawX, this.drawY);
}


}

Enemy.prototype.fire = function(startX, startY) {
    this.drawX = startX;
    this.drawY = startY;
}

// end of enemy functions





// event functions

function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow
         jet1.dy = -3;    
    }
    if (keyID === 39 ) { //right arrow
      jet1.direction = 1;
        jet1.dx = 3;    
    }
    if (keyID === 40 ) { //down arrow 
        jet1.dy = 3;   

    }
    if (keyID === 37 ) { //left arrow 
          jet1.dx = -3; 
          jet1.direction = -1;
    }
    if (keyID === 87) { //spacebar
       if(shootCounter >= shootLimit){
        jet1.fire = true;
        shootCounter = 0;
    }
       
    }
}

function checkKeyUp(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow 
     jet1.dy = 0; 
    }
    if (keyID === 39 ) { //right arrow 
      jet1.dx = 0; 
    }
    if (keyID === 40 ) { //down arrow 
      jet1.dy = 0; 
    }
    if (keyID === 37 ) { //left arrow 
      jet1.dx = 0; 
    }
    if (keyID === 87) { //spacebar
        jet1.fire = false;  
    }
}

// end of event functions

I have detected the problem myself, but I don't know what to do about it. If I remove the line that I've marked in the code in my collision detection method, then the boss will spawn without problems. I have two of this and I suppose it is something about a loop in a loop in a loop which have to loop multiple times. But I don't really understand how to solve that problem.


Jet.prototype.collision = function() {
   
 for (var i = 0; i < this.bullets.length; i++) {
   
  // Bullet with boss
    if(kills >= 50){    
if(this.bullets[i].drawX > bossX && this.bullets[i].drawX < bossX+100 && this.bullets[i].drawY > bossY && this.bullets[i].drawY < bossY+90 && this.bullets[i].bulletLife > 0 && this.bossLife > 0){
    this.collisiontest = true;
    if(this.collisiontest == true){
   this.bullets[i].bulletLife--; <<<<<<<<<<<<<<<<<<< THIS LINE MAKES IT SLOW!!
   this.bossLife--;
   this.collisiontest = false;
 }
}
}
    for (var j = 0; j < this.enemies.length; j++) {
        // Minuspoäng när fiender är utanför skärmen
            if(this.enemies[j].drawX > -10 && this.enemies[j].drawX < 0 && this.enemies[j].outScreen == false){
kills--;
this.enemies[j].outScreen = true;
            }

// Bullet with enemy
            if(this.bullets[i].drawX > this.enemies[j].drawX && this.bullets[i].drawX < this.enemies[j].drawX+50 && this.bullets[i].drawY+30 > this.enemies[j].drawY && this.bullets[i].drawY < this.enemies[j].drawY+25 && this.bullets[i].bulletLife > 0 && this.enemies[j].life > 0 ){
                this.enemies[j].life--;
                if(this.enemies[j].life < 1){
                    kills++;
                }
                 this.collisiontest = true;
                 if(this.collisiontest == true){
                this.bullets[i].bulletLife--;
                this.collisiontest = false;
              }
            }
        }
      } 
}

Well, there's one thing I would maybe try. Your Jet() uses var i, and so does Jet.prototype.collision. Using the keyword this may be invoking the var i from Jet() instead of the var i from Jet.prototype.collision. I'd try renaming one of those var i to something else and seeing if it helps.

Javascript is kind of weird about scope. The only time you get a new scope is with a function call. Loops and other constructs using braces do not automatically generate a scope. You have a function call which creates a new scope for the collision function, but then the keyword this declares a scope to be used (I think). Thus, you may be using the Jet() scope var i.

I hope that helps. Otherwise, hopefully one of the more experienced guys will know more.

Cheers.

I tried to change all my for variables to unique variables, but it didn't really make any difference. Or...it somehow works fine when I open it offline in my web browser and test the game, but once I get it online - then it all mess up when the boss comes and it is about that line that I pointed out. I don't get it?!

Out of curiosity, are you using the same browser when you check it online vs. offline? Probably an obvious question, but something to check.

This topic is closed to new replies.

Advertisement