0

我正在尝试学习和运行这个 JavaScript 脚本,以便创建基于 HTML5 的游戏。我正在努力找出这段代码中的错误。它不工作。Chrome 的开发工具说我没有明确定义x它何时显示var x = 0;"=。这是代码,有人可以帮我找到错误并建议我如何解决它吗?这是代码:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var player;
var playerImage = new Image();
var playerImage = 'http://jonah.pro/Block_Die/dev/src/player.gif';

var PlayerX = canvas.width / 2;
var PlayerY = canvas.width / 2;
var x = 0;
var y = 0;

function init() {
player.x = PlayerX + x;
player.y = PlayerY + y;
ctx.drawImage(playerImage, player.x, player.y);
};

document.onkeydown = function(e) {
if ( e.keyCode === 87 ) {
    y -= 2;
    alert("up!");
} //up

if ( e.keyCode === 83 ) {
    y += 2;
    alert("down!");
}//down
if ( e.keyCode === 65 ) {
    x -= 2;
    alert("left!");
}//left
if ( e.keyCode === 68 ) {
    x += 2;
    alert("right!");
}//right
}

init();
4

1 回答 1

2

您尝试访问播放器的 x 属性,但播放器没有 x / y 属性。

var player

应该

var player = {x:0,y:0}

您正在创建一个新的 Image 对象,但在您将其重新定义为字符串之后

var playerImage = new Image();
var playerImage = 'http://jonah.pro/Block_Die/dev/src/player.gif';

应该

var playerImage = new Image();
playerImage.src = 'http://jonah.pro/Block_Die/dev/src/player.gif';

更新:关于您的评论,这里是带有播放器精灵控件的更新版本。

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var playerImage = new Image();
playerImage.src = 'http://jonah.pro/Block_Die/dev/src/player.gif';

var PlayerX = canvas.width / 2;
var PlayerY = canvas.height / 2;

playerImage.onload = redraw;


function redraw() {
    ctx.clearRect (0 , 0 , canvas.width , canvas.height );
    ctx.drawImage(playerImage, PlayerX, PlayerY);
}

document.onkeydown = function(e) {
    if ( e.keyCode === 87 ) {
        PlayerY -= 2;
        redraw();
    } //up

    if ( e.keyCode === 83 ) {
        PlayerY += 2;
        redraw();
    }//down
    if ( e.keyCode === 65 ) {
        PlayerX -= 2;
        redraw();
    }//left
    if ( e.keyCode === 68 ) {
        PlayerX += 2;
        redraw();
    }//right
}

请注意,我清除了所有画布以重新绘制播放器元素(ctx.clearRect (x,y,width, height );),如果您有更多资产,则需要调整它。

在这里提琴

于 2013-11-13T19:16:33.687 回答