Chrome自带恐龙小游戏的源码研究(完)

  在上一篇《Chrome自带恐龙小游戏的源码研究(七)》中研究了恐龙与障碍物的碰撞检测,这一篇主要研究组成游戏的其它要素。

游戏分数记录

Chrome自带恐龙小游戏的源码研究(完)

  如图所示,分数及最高分记录显示在游戏界面的右上角,每达到100分就会出现闪烁特效,游戏第一次gameover时显示历史最高分。分数记录器由DistanceMeter构造函数实现,以下是它的全部代码:

 DistanceMeter.dimensions = {
WIDTH: 10, //每个字符的宽度
HEIGHT: 13, //每个字符的高
DEST_WIDTH: 11 //间隙
};
DistanceMeter.config = {
// 初始时记录的分数上限为5位数,即99999
MAX_DISTANCE_UNITS: 5, // 每隔100米距离记录器的数字出现闪动特效
ACHIEVEMENT_DISTANCE: 100, // 将移动距离转化为合理的数值所用的转化系数
COEFFICIENT: 0.025, // 每250ms闪动一次
FLASH_DURATION: 1000 / 4, // 闪动次数
FLASH_ITERATIONS: 3
};
/**
* 距离记录器
* @param {HTMLCanvasElement} canvas
* @param {Object} spritePos 雪碧图上的坐标.
* @param {number} canvasWidth
* @constructor
*/
function DistanceMeter(canvas, spritePos, canvasWidth) {
this.canvas = canvas;
this.canvasCtx = canvas.getContext('2d');
this.image = imgSprite;
this.spritePos = spritePos;
//相对坐标
this.x = 0;
this.y = 5; //最大分数
this.maxScore = 0;
//高分榜
this.highScore = 0; this.digits = [];
//是否进行闪动特效
this.acheivement = false;
this.defaultString = '';
//闪动特效计时器
this.flashTimer = 0;
//闪动计数器
this.flashIterations = 0;
this.invertTrigger = false; this.config = DistanceMeter.config;
//最大记录为万位数
this.maxScoreUnits = this.config.MAX_DISTANCE_UNITS;
this.init(canvasWidth);
} DistanceMeter.prototype = {
/**
* 初始化距离记录器为00000
* @param canvasWidth canvas的宽度
*/
init: function(canvasWidth) {
var maxDistanceStr = ''; this.calcXPos(canvasWidth);
for (var i = 0; i < this.maxScoreUnits; i++) {
this.draw(i, 0);
this.defaultString += '0';
maxDistanceStr += '9';
} //
this.maxScore = parseInt(maxDistanceStr);
},
/**
* 计算出xPos
* @param canvasWidth
*/
calcXPos: function(canvasWidth) {
this.x = canvasWidth - (DistanceMeter.dimensions.DEST_WIDTH * (this.maxScoreUnits + 1));
},
draw: function(digitPos, value, opt_highScore) {
var sourceWidth = DistanceMeter.dimensions.WIDTH;
var sourceHeight = DistanceMeter.dimensions.HEIGHT;
var sourceX = DistanceMeter.dimensions.WIDTH * value;
var sourceY = 0; var targetX = digitPos * DistanceMeter.dimensions.DEST_WIDTH;
var targetY = this.y;
var targetWidth = DistanceMeter.dimensions.WIDTH;
var targetHeight = DistanceMeter.dimensions.HEIGHT; sourceX += this.spritePos.x;
sourceY += this.spritePos.y; this.canvasCtx.save(); if (opt_highScore) {
// 将最高分放至当前分数的左边
var highScoreX = this.x - (this.maxScoreUnits * 2) * DistanceMeter.dimensions.WIDTH;
this.canvasCtx.translate(highScoreX, this.y);
} else {
this.canvasCtx.translate(this.x, this.y);
} this.canvasCtx.drawImage(this.image, sourceX, sourceY, sourceWidth, sourceHeight, targetX, targetY, targetWidth, targetHeight); this.canvasCtx.restore();
},
/**
* 将像素距离转化为“真实距离”
* @param distance 像素距离
* @returns {number} “真实距离”
*/
getActualDistance: function(distance) {
return distance ? Math.round(distance * this.config.COEFFICIENT) : 0;
},
/**
* 更新距离记录器
* @param {number} deltaTime
* @param {number} distance
* @returns {boolean} 是否播放声音
*/
update: function(deltaTime, distance) {
var paint = true;
var playSound = false; if (!this.acheivement) {
distance = this.getActualDistance(distance);
// 分数超过最大分数时增加至十万位999999
if (distance > this.maxScore && this.maxScoreUnits === this.config.MAX_DISTANCE_UNITS) {
this.maxScoreUnits++;
this.maxScore = parseInt(this.maxScore + '9');
} if (distance > 0) {
// 每100距离开始闪动特效并播放声音
if (distance % this.config.ACHIEVEMENT_DISTANCE === 0) {
this.acheivement = true;
this.flashTimer = 0;
playSound = true;
} // 让数字以0开头
var distanceStr = (this.defaultString + distance).substr( - this.maxScoreUnits);
this.digits = distanceStr.split('');
} else {
this.digits = this.defaultString.split('');
}
} else {
// 到达目标分数时闪动分数
if (this.flashIterations <= this.config.FLASH_ITERATIONS) {
this.flashTimer += deltaTime; if (this.flashTimer < this.config.FLASH_DURATION) {
paint = false;
} else if (this.flashTimer > this.config.FLASH_DURATION * 2) {
this.flashTimer = 0;
this.flashIterations++;
}
} else {
this.acheivement = false;
this.flashIterations = 0;
this.flashTimer = 0;
}
} // 非闪动时绘制分数
if (paint) {
for (var i = this.digits.length - 1; i >= 0; i--) {
this.draw(i, parseInt(this.digits[i]));
}
} this.drawHighScore();
return playSound;
},
//绘制高分榜
drawHighScore: function() {
this.canvasCtx.save();
this.canvasCtx.globalAlpha = .8; //让字符看起来颜色稍浅
for (var i = this.highScore.length - 1; i >= 0; i--) {
this.draw(i, parseInt(this.highScore[i], 10), true);
}
this.canvasCtx.restore();
},
setHighScore: function(distance) {
distance = this.getActualDistance(distance);
var highScoreStr = (this.defaultString + distance).substr( - this.maxScoreUnits);
//10和11分别对应雪碧图中的H、I
this.highScore = ['10', '11', ''].concat(highScoreStr.split(''));
},
//重置记录器为00000
reset: function() {
this.update(0);
this.acheivement = false;
}
};

GameOver

  恐龙和障碍物碰撞后,游戏结束,游戏界面显示gameover面板,该功能由GameOverPanel构造函数实现:

 GameOverPanel.dimensions = {
TEXT_X: 0,
TEXT_Y: 13,
TEXT_WIDTH: 191,
TEXT_HEIGHT: 11,
RESTART_WIDTH: 36,
RESTART_HEIGHT: 32
}; function GameOverPanel(canvas, textImgPos, restartImgPos, dimensions) {
this.canvas = canvas;
this.canvasCtx = canvas.getContext('2d');
this.canvasDimensions = dimensions;
this.textImgPos = textImgPos;
this.restartImgPos = restartImgPos;
this.draw();
} GameOverPanel.prototype = {
draw: function() {
var dimensions = GameOverPanel.dimensions; var centerX = this.canvasDimensions.WIDTH / 2; // Game over text
var textSourceX = dimensions.TEXT_X;
var textSourceY = dimensions.TEXT_Y;
var textSourceWidth = dimensions.TEXT_WIDTH;
var textSourceHeight = dimensions.TEXT_HEIGHT; var textTargetX = Math.round(centerX - (dimensions.TEXT_WIDTH / 2));
var textTargetY = Math.round((this.canvasDimensions.HEIGHT - 25) / 3);
var textTargetWidth = dimensions.TEXT_WIDTH;
var textTargetHeight = dimensions.TEXT_HEIGHT; var restartSourceWidth = dimensions.RESTART_WIDTH;
var restartSourceHeight = dimensions.RESTART_HEIGHT;
var restartTargetX = centerX - (dimensions.RESTART_WIDTH / 2);
var restartTargetY = this.canvasDimensions.HEIGHT / 2; textSourceX += this.textImgPos.x;
textSourceY += this.textImgPos.y; // Game over text from sprite.
this.canvasCtx.drawImage(imgSprite, textSourceX, textSourceY, textSourceWidth, textSourceHeight, textTargetX, textTargetY, textTargetWidth, textTargetHeight); // Restart button.
this.canvasCtx.drawImage(imgSprite, this.restartImgPos.x, this.restartImgPos.y, restartSourceWidth, restartSourceHeight, restartTargetX, restartTargetY, dimensions.RESTART_WIDTH, dimensions.RESTART_HEIGHT);
}
};
 function gameOver() {
cancelAnimationFrame(raq);
raq = 0;
crashed = true;
trex.update(0, Trex.status.CRASHED); distanceMeter.acheivement = false;
if (distanceRan > highestScore) {
highestScore = Math.ceil(distanceRan);
distanceMeter.setHighScore(highestScore);
} if (!gameOverPanel) {
gameOverPanel = new GameOverPanel(c, spriteDefinition.TEXT_SPRITE, spriteDefinition.RESTART, dimensions);
} else {
gameOverPanel.draw();
}
}

游戏重新开始

  GameOver后,按下Spacebar游戏重新开始,restart方法负责将游戏各个元素或数据重置:

 function restart() {
trex.reset();
Obstacle.obstacles = [];
h.reset();
night.reset();
crashed = false;
time = performance.now();
distanceRan = 0;
ctx.clearRect(0, 0, 600, 150);
distanceMeter.reset();
raq = requestAnimationFrame(draw, c);
}

游戏暂停

  当游戏窗口失去焦点时,游戏暂停,得到焦点时游戏继续。游戏通过注册三个事件来实现:

document.addEventListener('visibilitychange',onVisibilityChange);
window.addEventListener('blur',onVisibilityChange);
window.addEventListener('focus',onVisibilityChange);
 onVisibilityChange: function(e) {
if (document.hidden || document.webkitHidden || e.type == 'blur' || document.visibilityState != 'visible') {
this.stop();
} else if (!this.crashed) {
this.tRex.reset();
this.play();
}
},
stop: function() {
this.activated = false;
this.paused = true;
cancelAnimationFrame(this.raqId);
this.raqId = 0;
},
play: function() {
if (!this.crashed) {
this.activated = true;
this.paused = false;
this.tRex.update(0, Trex.status.RUNNING);
this.time = getTimeStamp();
this.update();
}
}

开场动画

  第一次开始游戏时,会有一个过渡动画,效果是地面逐渐展开,并且恐龙向前移动50像素。

 // CSS animation definition.
var keyframes = '@-webkit-keyframes intro { ' + 'from { width:' + Trex.config.WIDTH + 'px }' + 'to { width: ' + this.dimensions.WIDTH + 'px }' + '}';
document.styleSheets[0].insertRule(keyframes, 0); this.containerEl.addEventListener('webkitAnimationEnd', this.startGame.bind(this)); this.containerEl.style.webkitAnimation = 'intro .4s ease-out 1 both';
this.containerEl.style.width = this.dimensions.WIDTH + 'px'; //向前移动50像素
if (this.playingIntro && this.xPos < this.config.START_X_POS) {
this.xPos += Math.round((this.config.START_X_POS / this.config.INTRO_DURATION) * deltaTime);
}

游戏音效

  游戏准备了三种音效,分别是游戏点击空格键开始时、与障碍物碰撞时、每到达100分时。游戏在代码中放置了三个audio标签来存放音效,并且是base64形式,所以在播放时要经过解码,可以查阅文档了解AudioContext API的用法:

 function decodeBase64ToArrayBuffer(base64String) {
var len = (base64String.length / 4) * 3;
var str = atob(base64String);
var arrayBuffer = new ArrayBuffer(len);
var bytes = new Uint8Array(arrayBuffer); for (var i = 0; i < len; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes.buffer;
}
 var data = '........base64String.......';
var soundFx = {};
var soundSrc = data.substr(data.indexOf(',')+1);
var buffer = decodeBase64ToArrayBuffer(soundSrc);
var audioContext = new AudioContext();
audioContext.decodeAudioData(buffer,function(index,audioData) {
soundFx[index] = audioData;
}.bind(this,'audio1')); function playSound(soundBuffer) {
if (soundBuffer) {
var sourceNode = audioContext.createBufferSource();
sourceNode.buffer = soundBuffer;
sourceNode.connect(audioContext.destination);
sourceNode.start(0);
}
} window.onload = function() {
playSound(soundFx['audio1']);
};

对移动设备的处理  

  游戏还专门对移动设备进行了处理,包括屏幕大小的自适应,游戏速度调节,为高清屏加载高清素材等等。具体代码就不一一列出了。

  至此,对这个小游戏的代码研究结束,下面是完整的游戏:

 

Chrome自带恐龙小游戏的源码研究(完)

// this.config.CLEAR_TIME;
//如果是第一次跳跃并且没有播放开场动画,则播放开场动画
if (this.tRex.jumpCount == 1 && !this.playingIntro) {
this.playIntro();
}

if (this.playingIntro) {
this.horizon.update(0, this.currentSpeed, hasObstacles);
} else {
deltaTime = !this.started ? 0 : deltaTime;
this.horizon.update(deltaTime, this.currentSpeed, hasObstacles,
this.inverted);
}
var collision = hasObstacles &&
checkForCollision(this.horizon.obstacles[0], this.tRex);

if (!collision) {
this.distanceRan += this.currentSpeed * deltaTime / this.msPerFrame;

if (this.currentSpeed this.config.INVERT_FADE_DURATION) {
this.invertTimer = 0;
this.invertTrigger = false;
this.invert();
} else if (this.invertTimer) {
this.invertTimer += deltaTime;
} else {
var actualDistance =
this.distanceMeter.getActualDistance(Math.ceil(this.distanceRan));

if (actualDistance > 0) {
this.invertTrigger = !(actualDistance %
this.config.INVERT_DISTANCE);

if (this.invertTrigger && this.invertTimer === 0) {
this.invertTimer += deltaTime;
this.invert();
}
}
}
}
if (!this.crashed) {
this.tRex.update(deltaTime);
this.raq();
}
},
handleEvent: function(e) {
return (function(evtType, events) {
switch (evtType) {
case events.KEYDOWN:
case events.TOUCHSTART:
case events.MOUSEDOWN:
this.onKeyDown(e);
break;
case events.KEYUP:
case events.TOUCHEND:
case events.MOUSEUP:
this.onKeyUp(e);
break;
}
}.bind(this))(e.type, Runner.events);
},
startListening:function() {
document.addEventListener(Runner.events.KEYDOWN, this);
document.addEventListener(Runner.events.KEYUP, this);
document.addEventListener(Runner.events.MOUSEDOWN, this);
document.addEventListener(Runner.events.MOUSEUP, this);
},
stopListening:function() {
document.removeEventListener(Runner.events.KEYDOWN, this);
document.removeEventListener(Runner.events.KEYUP, this);
document.removeEventListener(Runner.events.MOUSEDOWN, this);
document.removeEventListener(Runner.events.MOUSEUP, this);
},
onKeyDown:function (e) {

if (e.target != this.detailsButton) {
if (!this.crashed && Runner.keycodes.JUMP[e.keyCode]) {
e.preventDefault();
if (!this.activated) {
this.loadSounds();
this.activated = true;
}
if (!this.tRex.jumping && !this.tRex.ducking) {
this.tRex.startJump(this.currentSpeed);
}
}
}
if (this.activated && !this.crashed && Runner.keycodes.DUCK[e.keyCode]) {

e.preventDefault();
if (this.tRex.jumping) {
// Speed drop, activated only when jump key is not pressed.
this.tRex.setSpeedDrop();
} else if (!this.tRex.jumping && !this.tRex.ducking) {
// Duck.
this.tRex.setDuck(true);
}
}
},
onKeyUp:function(e) {
var keyCode = String(e.keyCode);
var isjumpKey = Runner.keycodes.JUMP[keyCode] ||
e.type == Runner.events.TOUCHEND ||
e.type == Runner.events.MOUSEDOWN;

if (this.isRunning() && isjumpKey) {
e.preventDefault();
this.tRex.endJump();
} else if (Runner.keycodes.DUCK[keyCode]) {
e.preventDefault();
this.tRex.speedDrop = false;
this.tRex.setDuck(false);
} else if (this.crashed) {
e.preventDefault();
// Check that enough time has elapsed before allowing jump key to restart.
var deltaTime = getTimeStamp() - this.time;

if (Runner.keycodes.RESTART[keyCode] || this.isLeftClickOnCanvas(e) ||
(deltaTime >= this.config.GAMEOVER_CLEAR_TIME &&
Runner.keycodes.JUMP[keyCode])) {
e.preventDefault();
this.restart();
}
} else if (this.paused && isjumpKey) {
// Reset the jump state
e.preventDefault();
this.tRex.reset();
this.play();
}
},
isLeftClickOnCanvas: function(e) {
return e.button != null && e.button this.highestScore) {
this.highestScore = Math.ceil(this.distanceRan);
this.distanceMeter.setHighScore(this.highestScore);
}

// Reset the time clock.
this.time = getTimeStamp();
},
stop: function() {
this.activated = false;
this.paused = true;
cancelAnimationFrame(this.raqId);
this.raqId = 0;
},
play: function() {
if (!this.crashed) {
this.activated = true;
this.paused = false;
this.tRex.update(0, Trex.status.RUNNING);
this.time = getTimeStamp();
this.update();
}
},
restart: function() {
if (!this.raqId) {
this.playCount++;
this.runningTime = 0;
this.activated = true;
this.crashed = false;
this.distanceRan = 0;
this.setSpeed(this.config.SPEED);
this.time = getTimeStamp();
this.containerEl.classList.remove(Runner.classes.CRASHED);
this.clearCanvas();
this.distanceMeter.reset(this.highestScore);
this.horizon.reset();
this.tRex.reset();
//this.playSound(this.soundFx.BUTTON_PRESS);
this.invert(true);
this.update();
}
},
onVisibilityChange: function(e) {
if (document.hidden || document.webkitHidden || e.type == 'blur' ||
document.visibilityState != 'visible') {
this.stop();
} else if (!this.crashed) {
this.tRex.reset();
this.play();
}
},
playSound: function(soundBuffer) {
if (soundBuffer) {
var sourceNode = this.audioContext.createBufferSource();
sourceNode.buffer = soundBuffer;
sourceNode.connect(this.audioContext.destination);
sourceNode.start(0);
}
},
invert: function(reset) {
if (reset) {
a.classList.toggle(Runner.classes.INVERTED,this.invertTrigger);
//document.body.classList.toggle(Runner.classes.INVERTED,false);
this.invertTimer = 0;
this.inverted = false;
} else {
this.inverted = a.classList.toggle(Runner.classes.INVERTED,this.invertTrigger);

//this.inverted = document.body.classList.toggle(Runner.classes.INVERTED,this.invertTrigger);
}
}
};

window['Runner'] = Runner;

function decodeBase64ToArrayBuffer(base64String) {
var len = (base64String.length / 4) * 3;
var str = atob(base64String);
var arrayBuffer = new ArrayBuffer(len);
var bytes = new Uint8Array(arrayBuffer);

for (var i = 0; i this.bumpThreshold ? this.dimensions.WIDTH : 0;
},
draw:function() {
this.ctx.drawImage(imgSprite,
this.sourceXPos[0], this.spritePos.y,
this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT,
this.xPos[0],this.yPos,
this.dimensions.WIDTH,this.dimensions.HEIGHT);

this.ctx.drawImage(imgSprite,
this.sourceXPos[1], this.spritePos.y,
this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT,
this.xPos[1],this.yPos,
this.dimensions.WIDTH,this.dimensions.HEIGHT);

},
updateXPos:function(pos,increment) {
var line1 = pos,
line2 = pos === 0 ? 1 : 0;

this.xPos[line1] -= increment;
this.xPos[line2] = this.xPos[line1] + this.dimensions.WIDTH;

if(this.xPos[line1] 0;
}
};

//夜晚
//todo
NightMode.config = {
FADE_SPEED: 0.035, //淡入淡出速度
HEIGHT: 40, //月亮高度
MOON_SPEED: 0.25, //月亮移动速度
NUM_STARS: 2, //星星数量
STAR_SIZE: 9, //星星宽度
STAR_SPEED: 0.3,//星星速度
STAR_MAX_Y: 70, //星星在画布上出现的位置
WIDTH: 20 //半个月度宽度
};
NightMode.phases = [140,120,100,60,40,20,0];
function NightMode(canvas,spritePos,containerWidth) {
this.spritePos = spritePos;
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.containerWidth = containerWidth;
this.xPos = containerWidth - 50; //月亮的x坐标
this.yPos = 30; //月亮的y坐标
this.currentPhase = 0;
this.opacity = 0;
this.stars = []; //用于存储星星
this.drawStars = false;
this.placeStars(); //放置星星
}

NightMode.prototype = {
update:function(activated) {
if(activated && this.opacity == 0) {
this.currentPhase++;
if(this.currentPhase >= NightMode.phases.length) {
this.currentPhase = 0;
}
}

//淡入淡出
if(activated && (this.opacity 0) {
this.opacity -= NightMode.config.FADE_SPEED;
}

//移动月亮
if(this.opacity > 0) {
this.xPos = this.updateXPos(this.xPos, NightMode.config.MOON_SPEED);

//移动星星
if(this.drawStars) {
for (var i = 0; i = 0; i--) {
this.clouds[i].update(cloudSpeed);
}
var lastCloud = this.clouds[numClouds - 1];
if(numClouds lastCloud.cloudGap &&
this.cloudFrequency > Math.random()) {
this.addCloud();
}

this.clouds = this.clouds.filter(function(obj){
return !obj.remove;
});
} else {
this.addCloud();
}
},
updateObstacles: function(deltaTime, currentSpeed) {
// Obstacles, move to Horizon layer.
var updatedObstacles = this.obstacles.slice(0);

for (var i = 0; i 0) {
var lastObstacle = this.obstacles[this.obstacles.length - 1];

if (lastObstacle && !lastObstacle.followingObstacleCreated &&
lastObstacle.isVisible() &&
(lastObstacle.xPos + lastObstacle.width + lastObstacle.gap) 1) {
this.obstacleHistory.splice(Runner.config.MAX_OBSTACLE_DUPLICATION);
}
},
duplicateObstacleCheck:function(nextObstacleType) {
var duplicateCount = 0;

for(var i = 0; i = Runner.config.MAX_OBSTACLE_DUPLICATION;
},
reset: function() {
this.obstacles = [];
this.horizonLine.reset();
this.nightMode.reset();
},
resize: function(width, height) {
this.canvas.width = width;
this.canvas.height = height;
},
addCloud: function() {
this.clouds.push(new Cloud(this.canvas, this.spritePos.CLOUD,this.dimensions.WIDTH));
}
};

Obstacle.MAX_GAP_COEFFICIENT = 1.5;
Obstacle.MAX_OBSTACLE_LENGTH = 3;
Obstacle.types = [
{
type: 'CACTUS_SMALL',
width: 17,
height: 35,
yPos: 105,
multipleSpeed: 4,
minGap: 120,
minSpeed: 0,
collisionBoxes: [
new CollisionBox(0, 7, 5, 27),
new CollisionBox(4, 0, 6, 34),
new CollisionBox(10, 4, 7, 14)
]
},
{
type: 'CACTUS_LARGE',
width: 25,
height: 50,
yPos: 90,
multipleSpeed: 7,
minGap: 120,
minSpeed: 0,
collisionBoxes: [
new CollisionBox(0, 12, 7, 38),
new CollisionBox(8, 0, 7, 49),
new CollisionBox(13, 10, 10, 38)
]
},
{
type: 'PTERODACTYL',
width: 46,
height: 40,
yPos: [ 100, 75, 50 ], // Variable height. 高、中、低三种高度
yPosMobile: [ 100, 50 ], // Variable height mobile.
multipleSpeed: 999,
minSpeed: 8.5,
minGap: 150,
collisionBoxes: [
new CollisionBox(15, 15, 16, 5),
new CollisionBox(18, 21, 24, 6),
new CollisionBox(2, 14, 4, 3),
new CollisionBox(6, 10, 4, 7),
new CollisionBox(10, 8, 6, 9)
],
numFrames: 2,
frameRate: 1000/6,
speedOffset: .8
}
];

function Obstacle(ctx,type,spriteImgPos,dimensions,gapCoefficient,speed,opt_xOffset) {
this.ctx = ctx;
this.spritePos = spriteImgPos;
//障碍物类型(仙人掌、翼龙)
this.typeConfig = type;
this.gapCoefficient = gapCoefficient;
this.size = getRandomNum(1,Obstacle.MAX_OBSTACLE_LENGTH);
this.dimensions = dimensions;
this.remove = false;
this.xPos = dimensions.WIDTH + (opt_xOffset || 0);
this.yPos = 0;
this.width = 0;
this.collisionBoxes = [];
this.gap = 0;
this.speedOffset = 0;

// For animated obstacles.
this.currentFrame = 0;
this.timer = 0;

this.init(speed);
}

Obstacle.prototype = {
init:function(speed) {
this.cloneCollisionBoxes();
//若multipleSpeed大于移动速度,则只出现一个障碍物
if (this.size > 1 && this.typeConfig.multipleSpeed > speed) {
this.size = 1;
}

this.width = this.typeConfig.width * this.size;

if (Array.isArray(this.typeConfig.yPos)) {
var yPosConfig = this.typeConfig.yPos;
this.yPos = yPosConfig[getRandomNum(0, yPosConfig.length - 1)];
} else {
this.yPos = this.typeConfig.yPos;
}

this.draw();

if (this.size > 1) {
this.collisionBoxes[1].width = this.width - this.collisionBoxes[0].width -
this.collisionBoxes[2].width;

this.collisionBoxes[2].x = this.width - this.collisionBoxes[2].width;
}

if (this.typeConfig.speedOffset) {
this.speedOffset = Math.random() > 0.5 ? this.typeConfig.speedOffset :
-this.typeConfig.speedOffset;
}

this.gap = this.getGap(this.gapCoefficient, speed);
},
draw:function() {
var sourceWidth = this.typeConfig.width;
var sourceHeight = this.typeConfig.height;
var sourceX = (sourceWidth * this.size) * (0.5 * (this.size - 1)) +
this.spritePos.x;

// Animation frames.
if (this.currentFrame > 0) {
sourceX += sourceWidth * this.currentFrame;
}
this.ctx.drawImage(imgSprite,
sourceX, this.spritePos.y,
sourceWidth * this.size, sourceHeight,
this.xPos, this.yPos,
sourceWidth * this.size, sourceHeight);
},
update:function(deltaTime, speed) {
if (!this.remove) {
if (this.typeConfig.speedOffset) {
speed += this.speedOffset;
}
this.xPos -= Math.floor((speed * FPS / 1000) * deltaTime);

// Update frame
if (this.typeConfig.numFrames) {
this.timer += deltaTime;
if (this.timer >= this.typeConfig.frameRate) {
this.currentFrame =
this.currentFrame == this.typeConfig.numFrames - 1 ?
0 : this.currentFrame + 1;
this.timer = 0;
}
}
this.draw();

if (!this.isVisible()) {
this.remove = true;
}
}
},
getGap: function(gapCoefficient, speed) {
var minGap = Math.round(this.width * speed +
this.typeConfig.minGap * gapCoefficient);
var maxGap = Math.round(minGap * Obstacle.MAX_GAP_COEFFICIENT);
return getRandomNum(minGap, maxGap);
},
isVisible: function() {
return this.xPos + this.width > 0;
},
cloneCollisionBoxes: function() {
var collisionBoxes = this.typeConfig.collisionBoxes;

for (var i = collisionBoxes.length - 1; i >= 0; i--) {
this.collisionBoxes[i] = new CollisionBox(collisionBoxes[i].x,
collisionBoxes[i].y, collisionBoxes[i].width,
collisionBoxes[i].height);
}
}
};

DistanceMeter.dimensions = {
WIDTH: 10,
HEIGHT: 13,
DEST_WIDTH: 11
};
DistanceMeter.yPos = [0, 13, 27, 40, 53, 67, 80, 93, 107, 120];
DistanceMeter.config = {
// Number of digits.
MAX_DISTANCE_UNITS: 5,

// Distance that causes achievement animation.
ACHIEVEMENT_DISTANCE: 100,

// Used for conversion from pixel distance to a scaled unit.
COEFFICIENT: 0.025,

// Flash duration in milliseconds.
FLASH_DURATION: 1000 / 4,

// Flash iterations for achievement animation.
FLASH_ITERATIONS: 3
};

function DistanceMeter(canvas, spritePos, canvasWidth) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.image = imgSprite;
this.spritePos = spritePos;
this.x = 0;
this.y = 5;

this.currentDistance = 0;
this.maxScore = 0;
this.highScore = 0;
this.container = null;

this.digits = [];
this.acheivement = false;
this.defaultString = '';
this.flashTimer = 0;
this.flashIterations = 0;
this.invertTrigger = false;

this.config = DistanceMeter.config;
this.maxScoreUnits = this.config.MAX_DISTANCE_UNITS;
this.init(canvasWidth);
}

DistanceMeter.prototype = {
init: function(width) {
var maxDistanceStr = '';

this.calcXPos(width);
this.maxScore = this.maxScoreUnits;
for (var i = 0; i this.maxScore && this.maxScoreUnits ==
this.config.MAX_DISTANCE_UNITS) {
this.maxScoreUnits++;
this.maxScore = parseInt(this.maxScore + '9');
} else {
this.distance = 0;
}

if (distance > 0) {
// Acheivement unlocked
if (distance % this.config.ACHIEVEMENT_DISTANCE == 0) {
// Flash score and play sound.
this.acheivement = true;
this.flashTimer = 0;
playSound = true;
}

// Create a string representation of the distance with leading 0.
var distanceStr = (this.defaultString +
distance).substr(-this.maxScoreUnits);
this.digits = distanceStr.split('');
} else {
this.digits = this.defaultString.split('');
}
} else {
// Control flashing of the score on reaching acheivement.
if (this.flashIterations
this.config.FLASH_DURATION * 2) {
this.flashTimer = 0;
this.flashIterations++;
}
} else {
this.acheivement = false;
this.flashIterations = 0;
this.flashTimer = 0;
}
}

// Draw the digits if not flashing.
if (paint) {
for (var i = this.digits.length - 1; i >= 0; i--) {
this.draw(i, parseInt(this.digits[i]));
}
}

this.drawHighScore();
return playSound;
},
drawHighScore: function() {
this.ctx.save();
this.ctx.globalAlpha = .8;
for (var i = this.highScore.length - 1; i >= 0; i--) {
this.draw(i, parseInt(this.highScore[i], 10), true);
}
this.ctx.restore();
},
setHighScore: function(distance) {
distance = this.getActualDistance(distance);
var highScoreStr = (this.defaultString +
distance).substr(-this.maxScoreUnits);

this.highScore = ['10', '11', ''].concat(highScoreStr.split(''));
},
reset: function() {
this.update(0);
this.acheivement = false;
}
};

/**
* 碰撞检测盒子
* @param x {number} x坐标
* @param y {number} y坐标
* @param w {number} 宽度
* @param h {number} 高度
*/
//todo:碰撞检测
function CollisionBox(x,y,w,h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}

function checkForCollision(obstacle, tRex, opt_canvasCtx) {
var obstacleBoxXPos = Runner.defaultDimensions.WIDTH + obstacle.xPos;
var tRexBox = new CollisionBox(
tRex.xPos + 1,
tRex.yPos + 1,
tRex.config.WIDTH - 2,
tRex.config.HEIGHT - 2);
var obstacleBox = new CollisionBox(
obstacle.xPos + 1,
obstacle.yPos + 1,
obstacle.typeConfig.width * obstacle.size - 2,
obstacle.typeConfig.height - 2);

if (opt_canvasCtx) {
drawCollisionBoxes(opt_canvasCtx, tRexBox, obstacleBox);
}
if (boxCompare(tRexBox, obstacleBox)) {
var collisionBoxes = obstacle.collisionBoxes;
var tRexCollisionBoxes = tRex.ducking ?
Trex.collisionBoxes.DUCKING : Trex.collisionBoxes.RUNNING;

for (var t = 0; t obstacleBoxX &&
tRexBox.y obstacleBox.y) {
crashed = true;
}

return crashed;
}

function drawCollisionBoxes(canvasCtx, tRexBox, obstacleBox) {
canvasCtx.save();
canvasCtx.lineWidth = 0.5;
canvasCtx.strokeStyle = '#f00';
canvasCtx.strokeRect(tRexBox.x+0.5, tRexBox.y+0.5, tRexBox.width, tRexBox.height);

canvasCtx.strokeStyle = '#0f0';
canvasCtx.strokeRect(obstacleBox.x+0.5, obstacleBox.y+0.5,
obstacleBox.width, obstacleBox.height);
canvasCtx.restore();
}

Trex.config = {
DROP_VELOCITY: -5, //下落速度
GRAVITY: 0.6, //重力
HEIGHT: 47, //站立时高度
HEIGHT_DUCK: 25, //闪躲时高度
INIITAL_JUMP_VELOCITY: -10,//初始起跳速度
INTRO_DURATION: 1500,
MAX_JUMP_HEIGHT: 30, //最大起跳高度
MIN_JUMP_HEIGHT: 30, //最小起跳高度
SPEED_DROP_COEFFICIENT: 3,
SPRITE_WIDTH: 262, //雪碧图霸王龙部分的宽度(不包含闪避动作)
START_X_POS: 50, //在画布的起始位置
WIDTH: 44, //站立时宽度
WIDTH_DUCK: 59 //闪避时宽度
};

Trex.status = {
CRASHED: 'CRASHED', //碰到障碍物
DUCKING: 'DUCKING', //闪避
JUMPING: 'JUMPING', //跳跃
RUNNING: 'RUNNING', //跑动
WAITING: 'WAITING' //等待
};

Trex.BLINK_TIMING = 3000;

Trex.collisionBoxes = {
DUCKING:[
new CollisionBox(1,18,55,25)
],
RUNNING: [
new CollisionBox(22, 0, 17, 16),
new CollisionBox(1, 18, 30, 9),
new CollisionBox(10, 35, 14, 8),
new CollisionBox(1, 24, 29, 5),
new CollisionBox(5, 30, 21, 4),
new CollisionBox(9, 34, 15, 4)
]
};

Trex.animFrames = {
WAITING: {
frames: [44, 0],
msPerFrame: 1000 / 3
},
RUNNING: {
frames: [88, 132],
msPerFrame: 1000 / 12
},
CRASHED: {
frames: [220],
msPerFrame: 1000 / 60
},
JUMPING: {
frames: [0],
msPerFrame: 1000 / 60
},
DUCKING: {
frames: [262, 321],
msPerFrame: 1000 / 8
}
};

function Trex(canvas,spritePos) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.spritePos = spritePos;
this.xPos = 0;
this.yPos = 0;
//站立时的Y轴坐标
this.groundYPos = 0;
this.currentFrame = 0;
this.currentAnimFrames = [];
this.blinkDelay = 0;
this.animStartTime = 0;
this.timer = 0;
this.msPerFrame = 1000 / FPS;
this.config = Trex.config;
//当前的动作为等待状态
this.status = Trex.status.WAITING;

this.jumping = false; //是否跳跃
this.ducking = false; //是否闪避
this.jumpVelocity = 0;
this.reachedMinHeight = false;
this.speedDrop = false;
this.jumpCount = 0;
this.jumpspotX = 0; //空降着陆点

this.init();
}
Trex.prototype = {
init:function() {
this.blinkDelay = this.setBlinkDelay();
this.groundYPos = Runner.defaultDimensions.HEIGHT - this.config.HEIGHT -
Runner.config.BOTTOM_PAD;
this.yPos = this.groundYPos;

this.minJumpHeight = this.groundYPos - this.config.MIN_JUMP_HEIGHT;
this.draw(0,0);
this.update(0,Trex.status.WAITING);
},
setJumpVelocity: function(setting) {
this.config.INIITAL_JUMP_VELOCITY = -setting;
this.config.DROP_VELOCITY = -setting / 2;
},
update:function(deltaTime,opt_status) {
this.timer += deltaTime;
if(opt_status) {
this.status = opt_status;
this.currentFrame = 0;
this.msPerFrame = Trex.animFrames[opt_status].msPerFrame;
this.currentAnimFrames = Trex.animFrames[opt_status].frames;

if(opt_status == Trex.status.WAITING) {
this.animStartTime = getTimeStamp();
this.setBlinkDelay();
}
}
if (this.playingIntro && this.xPos = this.msPerFrame) {
this.currentFrame = this.currentFrame ==
this.currentAnimFrames.length - 1 ? 0 : this.currentFrame + 1;
this.timer = 0;
}

if (this.speedDrop && this.yPos == this.groundYPos) {
this.speedDrop = false;
this.setDuck(true);
}
},
setBlinkDelay: function() {
this.blinkDelay = Math.ceil(Math.random() * Trex.BLINK_TIMING);
},
blink: function(time) {
var deltaTime = time - this.animStartTime;

if (deltaTime >= this.blinkDelay) {
this.draw(this.currentAnimFrames[this.currentFrame], 0);

if (this.currentFrame == 1) {
// Set new random delay to blink.
this.setBlinkDelay();
this.animStartTime = time;
}
}
},
startJump:function(speed) {
if(!this.jumping) {
this.update(0, Trex.status.JUMPING);
this.jumpVelocity = this.config.INIITAL_JUMP_VELOCITY - (speed / 10);
this.jumping = true;
this.reachedMinHeight = false;
this.speedDrop = false;
}
},
endJump: function() {
if (this.reachedMinHeight && this.jumpVelocity this.groundYPos) {
this.reset();
this.jumpCount++;
}

this.update(deltaTime);
},
setSpeedDrop: function() {
this.speedDrop = true;
this.jumpVelocity = 1;
},
setDuck: function(isDucking) {
if (isDucking && this.status != Trex.status.DUCKING) {
this.update(0, Trex.status.DUCKING);
this.ducking = true;
} else if (this.status == Trex.status.DUCKING) {
this.update(0, Trex.status.RUNNING);
this.ducking = false;
}
},
draw:function(x,y) {
var sourceX = x;
var sourceY = y;
var sourceWidth = this.ducking && this.status != Trex.status.CRASHED ?
this.config.WIDTH_DUCK : this.config.WIDTH;
var sourceHeight = this.config.HEIGHT;
sourceX += this.spritePos.x;
sourceY += this.spritePos.y;

if (this.ducking && this.status != Trex.status.CRASHED) {
this.ctx.drawImage(imgSprite, sourceX, sourceY,
sourceWidth, sourceHeight,
this.xPos, this.yPos,
this.config.WIDTH_DUCK, this.config.HEIGHT);
} else {
if (this.ducking && this.status == Trex.status.CRASHED) {
this.xPos++;
}

this.ctx.drawImage(imgSprite, sourceX, sourceY,
sourceWidth, sourceHeight,
this.xPos, this.yPos,
this.config.WIDTH, this.config.HEIGHT);
}
},
reset: function() {
this.yPos = this.groundYPos;
this.jumpVelocity = 0;
this.jumping = false;
this.ducking = false;
this.update(0, Trex.status.RUNNING);
this.midair = false;
this.speedDrop = false;
this.jumpCount = 0;
}
};

var now = getTimeStamp();

//不写onload方法就显示不出图片
window.onload = function() {
var runner = new Runner('.interstitial-wrapper');
};
// ]]>

总结

  通过对这个游戏的源码进行研究,从中收获了不少干货,对2d游戏的制作思路有一定的启发,特别是基于时间的运动有了进一步的认识。游戏大致可以划分为以下功能:

Chrome自带恐龙小游戏的源码研究(完)

大部分构造函数里都包含了一个名为update的方法,在每次GameLoop里调用以更新该游戏元件的状态,并根据条件判断是否在画布上绘制(draw)。

暂时就想到这么多,接下来就是以开发一个2D游戏为目标努力了。

上一篇:Hadoop 分布式文件系统:架构和设计


下一篇:Spring的2个思想