-1

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

    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

谢谢。

4

2 回答 2

1

在 chrome 中,游戏会生成一个停止执行的错误。var 游戏之后;游戏是未定义的,那么当你做 game.fps = something时,就像你在做undefined.fps = something一样,javascript 会生气。第一个补丁是做var game = {}

而且我不明白您为什么要在循环中一次又一次地创建 bgImage 和 player 。即使这样有效,也可能会产生问题。

    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);  

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

于 2012-05-10T11:01:57.330 回答
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
}

请注意,这过于简单化了,因为图像预加载是一个有很多陷阱的领域。但我想你会明白的。

顺便说一句,是一个关于游戏逻辑和所有东西画布的非常好的教程。

于 2012-05-10T11:06:44.660 回答