sc8ing
sc8ing

Reputation: 399

My game plays itself?

I've been making a canvas game in HTML5 and am new to a lot of it. I would like to use solely javascript to create my elements too (it is easier to embed into other sites this way and I feel it is cleaner). I had my game reloading in order to play again, but I want to be able to keep track of the score and multiple other variables without having to put each into the URL (which I have been doing) to make it seem like the game is still going. I'm also going to add "power ups" and other things that need to be "remembered" by the script.

Anyways, here's my question. When one player kills another, the game will play itself for a while and make my computer very slow until I reload the page. Why is it doing this? I cleared the interval for the main function (which loops the game and keeps everything running) and this used to make everything stop moving - it no longer does. What's wrong here?

This is my game: http://dl.dropbox.com/u/11168436/game/game.html

Controls: Move the skier with arrow keys and shoot with M (you shoot in the direction you were last moving in). The snowboarder is moved with ESDF and shoots with Q.

Thanks for your time.

Upvotes: 0

Views: 159

Answers (2)

Loktar
Loktar

Reputation: 35309

Ok heres what was basically happening, the variable interval existed in different scopes. So you were attempting to clear an interval.. but it wasn't the correct scope, so the var interval was really never being cleared (also you were using the incorrect syntax for clearing an interval).

Working Demo

You should learn more about function scope. You had var interval in a few different spots, one global and one locally in a function. This creates two seperate variables named interval. Heres a quick example,

var a = 10;
function(){
    var a = 1;
    console.log(a);
   // a will equal 1

}

console.log(a);
// a will equal 10

Anyway what I did to fix it was declared a global variable for interval and that variable is the only one used now for clearing ect.

Next issue I saw is you were using

interval = window.clearInterval(interval)

you only need to call

window.clearInterval(interval)

Its a good first attempt just keep learning :). Hopefully you understand what I did in the working example. Just compare it to your code, theres only a few minor differences all related to the scope of your variable interval

Upvotes: 4

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6116

These line may be the culprit:

var interval = window.setInterval(main, 1);

Bring that interval up to say, 30, and your problem should go away.

Upvotes: 0

Related Questions