我正在用HTML5和JavaScript制作我的第一款游戏。我正在使用Tileset类和Sprite类。 Tileset类获取完整的spritesheet,然后在ctx.drawImage()的一侧,我将tileset分成单独的图像。当我在Chrome中运行并打开控制台时,当我尝试access the tileset information使用时会出现undefined
。应该提出Tileset {image: img, tileWidth: 24, tileHeight: 30}
。所有相关代码都包含在下面。
For a quick and more simple example of what should be happening
Tileset类:
function Tileset(image, tileWidth, tileHeight) {
this.image = new Image();
game.images ++;
this.image.onload = imageLoaded;
this.image.src = image;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
}
Sprite类:
function Sprite(stateAnimations, startingState, x, y, width, height, speed) {
this.stateAnimations = stateAnimations;
this.currentState = startingState;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
Tileset初始化程序:
var playerTiles = new Tileset('playerSpritesheet.png', 24, 30);
Sprite初始化程序:
var player = new Sprite({'down': playerDownAnim}, 'down', canvas.width / 2, canvas.height / 2, 24, 30, 150);
Sprite的动画:
var playerDownAnim = new Animation(playerTiles, ['0,0','1,0','2,0'], 150);
最后,drawSprite()函数:
function drawSprite(sprite) {
ctx.drawImage(
sprite.stateAnimations[sprite.currentState].tileset.image,
sprite.stateAnimations[sprite.currentState].frames[sprite.stateAnimations[sprite.currentState].currentFrame].split(',')[0] * sprite.stateAnimations[sprite.currentState].tileset.tileWidth,
sprite.stateAnimations[sprite.currentState].frames[sprite.stateAnimations[sprite.currentState].currentFrame].split(',')[1] * sprite.stateAnimations[sprite.currentState].tileset.tileHeight,
sprite.stateAnimations[sprite.currentState].tileset.tileWidth,
sprite.stateAnimations[sprite.currentState].tileset.tileHeight,
Math.round(sprite.x),
Math.round(sprite.y),
sprite.width,
sprite.height
);
}
这是我的sprite sheet
请告诉我是否需要更多上下文代码或将代码放在其他地方,例如jsFiddle或其他东西。
感谢您的所有答案。