[摘要][]; this.cellIndex = 0; } SpriteSheetPainter.prototype = { advance:function(){ if(this.ce...
[];
this.cellIndex = 0;
}
SpriteSheetPainter.prototype = {
advance:function(){
if(this.cellIndex === this.cells.length-1){
this.cellIndex = 0;
}
else this.cellIndex++;
},
paint:function(sprite){
var cell = this.cells[this.cellIndex];
context.drawImage(spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left , sprite.top , cell.w , cell.h);
}
}
而普通的绘制器就更简单了,直接写一个painter,把要画的什么东西都写进去就行了。
有了精灵类和精灵表绘制器后,我们就可以把星星,飞机,子弹,爆炸对象都写出来了:下面是整个allSprite.js的代码:
JavaScript Code复制内容到剪贴板
(function(W){
"use strict"
var planWidth = 24,
planHeight = 24,
missleWidth = 70,
missleHeight = 70,
boomWidth = 60;
//精灵类
W.Sprite = function(name , painter , behaviors , args){
if(name !== undefined) this.name = name;
if(painter !== undefined) this.painter = painter;
this.top = 0;
this.left = 0;
this.width = 0;
this.height = 0;
this.velocityX = 3;
this.velocityY = 2;
this.visible = true;
this.animating = false;
this.behaviors = behaviors;
this.rotateAngle = 0;
this.blood = 50;
this.fullBlood = 50;
if(name==="plan"){
this.rotateSpeed = 0.05;
this.rotateLeft = false;
this.rotateRight = false;
this.fire = false;
this.firePerFrame = 10;
this.fireLevel = 1;
}else if(name==="star"){
this.width = Math.random()*2;
this.speed = 1*this.width/2;
this.lightLength = 5;
this.cacheCanvas = document.createElement("canvas");
this.cacheCtx = this.cacheCanvas.getContext('2d');
this.cacheCanvas.width = this.width+this.lightLength*2;
this.cacheCanvas.height = this.width+this.lightLength*2;
this.painter.cache(this);
}else if(name==="badPlan"){
this.badKind = 1;
this.speed = 2;
this.rotateAngle = Math.PI;
}else if(name==="missle"){
this.width = missleWidth;
}else if(name==="boom"){
this.width = boomWidth;
}else if(name==="food"){
this.width = 40;
this.speed = 3;
this.kind = "LevelUP"
}
this.toLeft = false;
this.toTop = false;
this.toRight = false;
this.toBottom = false;
this.outArcRadius = Math.sqrt((this.width/2*this.width/2)*2);
if(args){
for(var arg in args){
this[arg] = args[arg];
}
}
}
Sprite.prototype = {
constructor:Sprite,
paint:function(){
if(this.name==="badPlan"){this.update();}
if(this.painter !== undefined && this.visible){
if(this.name!=="badPlan") {
this.update();
}
if(this.name==="plan"
关键词:运用HTML5 Canvas制作一个容易的打飞机游戏