JavaScript游戏循环不起作用

时间:2012-05-10 10:53:31

标签: javascript loops

我正在尝试制作一款游戏。这是我的代码(非常基本):

    var canvas = document.createElement("canvas");
var gameCanvas = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);

// Global variables
var game;
game.fps = 60;
game._intervalId = setInterval(game.run, 1000 / game.fps);

// Game loop
game.run = function() {
    game.draw();
};

// Functions
game.draw = function() {
    // Background image
    var bgImage = new Image();
    bgImage.src = "img/background.png";
    // Player image
    var playerImage = new Image();
    playerImage.src = "img/player.png";
    // Draw
    gameCanvas.drawImage(bgImage, 0, 0);
    gameCanvas.drawImage(playerImage, 10, 10);      
}

// Game over
document.getElementById('end').onclick = function stop(){
    clearInterval(game._intervalId);    
}

// Run
window.onload = game.run();

游戏无法正常运行。我做错了什么,或者我错过了什么?以下是该页面的链接:http://dl.dropbox.com/u/33213779/Game/demo_me.html

感谢。

2 个答案:

答案 0 :(得分:1)

在Chrome中,游戏会生成一个停止执行的错误。 var游戏后;游戏是未定义的,然后你做 game.fps =某事,就像你在做 undefined.fps =某事,并且javascript生气。第一个补丁是 var game = {}

我不明白你为什么一次又一次地在循环中创建bgImage和播放器。即使这样可行,也可能产生问题。

    var canvas = document.createElement("canvas");
    var gameCanvas = canvas.getContext("2d");
    canvas.width = 500;
    canvas.height = 500;

      canvas.setAttribute("style","border:1px solid red");
    document.body.appendChild(canvas);

    // Global variables
    var game = {};
    game.fps = 60;


    // Game loop
    game.run = function() {
        game.draw();
    };

    // Resource loader
    game.loader = function() {
        // Background image
        game.bgImage = new Image();
        game.bgImage.src = "img/background.png";

        // Player image
        game.playerImage = new Image();

        game.playerImage.src = "img/player.png";
    };                 

    // Functions
    game.draw = function() {
        // Draw
        gameCanvas.drawImage(game.bgImage, 0, 0);
        gameCanvas.drawImage(game.playerImage, 10, 10);     
    }
            game.loader();
    game._intervalId = setInterval(game.run, 1000 / game.fps);  

此版本的代码似乎可以按预期工作。

答案 1 :(得分:1)

我可以从你写的内容中找出两个问题。

首先,你必须将你的游戏变量作为一个对象:

var game = {}; // = {} initializes a new Object
game.fps = 60;
....

第二个问题是你没有预加载你的图像源(而是每秒加载它们60次....)这样画布就无法访问它们,因为它们仍然被加载。

相反,您可以使用这样的机制:

var bgImage = new Image();
bgImage.src = "img/background.png";
bgImage.onload = checkPreload;

var playerImage = new Image();
playerImage.src = "img/player.png";
playerImage.onload = checkPreload;

var loadedPics = 0;
function checkPreload(){
loadedPics++;
if (loadedPics == 2){
buildGame(); //start game
}
}

function buildGame(){
//inside this function you should be safe to refer to bgImage and playerImage
}

请注意,这是非常过度简化,因为图像预加载是一个受到很多陷阱困扰的区域。但我想你会明白的。

顺便说一下, this 是一个非常好的游戏逻辑和所有画布教程。