-1

我从一个小型 HTML5 游戏开始,这是我正在做的第一个游戏。目前,我正在创建一个保存变量的函数,我真的不知道它叫什么,我只记得如何从教程中做到这一点。无论如何,我正在尝试使用“this”设置一些变量,但它似乎没有得到值。这是我认为导致问题的代码:

function ship() {
    this.width = 100;
    this.height = 75;
    this.drawX = gameWidth/2 - this.width/2;
    this.drawY = gameHeight + this.height;
}

this.drawX 和 Y 然而,似乎没有得到一个值。另外,我确信 gameHeight 和 gameWidth 有一个值。

编辑:这是绘图功能和其余代码:

var player = new ship();

var gameWidth  = canvasShip.width;
var gameHeight = canvasShip.height;

var sprites = new Image();
sprites.src = 'images/spriteSheet.png';

var canvasPlayer = document.getElementById('canvasShip');
var ctxPlayer = canvasPlayer.getContext('2d');

//Clear any canvas
function clearCtx(canvas) { 
    canvas.clearRect(0,0,gameWidth,gameHeight);
}

//Ship object, the player
function ship() {
    this.width = 100;
    this.height = 75;
    console.log(gameWidth,gameHeight);
    this.drawX = gameWidth/2 - this.width/2;
    this.drawY = gameHeight + this.height;
}

ship.prototype.draw = function() {
    clearCtx(ctxPlayer);
    ctxPlayer.drawImage(sprites,0,0,this.width,this.height,this.drawX,this.drawY, this.width, this.height);
}
4

1 回答 1

2

您代码中的这一部分看起来很可疑:

var player = new ship();

var gameWidth  = canvasShip.width;
var gameHeight = canvasShip.height;

在 的构造函数中,和ship()的值是。gameWidthgameHeightundefined

反转语句应该按预期工作:

var gameWidth  = canvasShip.width,
gameHeight = canvasShip.height,
player = new ship();

这是 JavaScript 查看您的代码的方式:

var gameWidth, gameHeight, player, ship;

ship = function() { ... }

player = new ship();
gameWidth = 123;
gameHeight = 456;

get 的声明ship()在有时被称为“提升”的过程中向上移动,这使得它的行为方式变得更加明显。

于 2012-10-22T03:30:11.300 回答