使用JavaScript和Canvas开发游戏(五)
nbsp;
if
(y==0) newScrollPosition[1] = yScroll *
this
.scrollFactor;
24 |
areaDrawn = this .drawRepeat(canvas, newPosition, newFillArea, newScrollPosition); |
28 |
this .drawRepeat = function (canvas, newPosition, newFillArea, newScrollPosition) |
31 |
var xOffset = Math.abs(newScrollPosition[0]) % this .image.width; |
32 |
var yOffset = Math.abs(newScrollPosition[1]) % this .image.height; |
33 |
var left = newScrollPosition[0]<0? this .image.width-xOffset:xOffset; |
34 |
var top = newScrollPosition[1]<0? this .image.height-yOffset:yOffset; |
35 |
var width = newFillArea[0] < this .image.width-left?newFillArea[0]: this .image.width-left; |
36 |
var height = newFillArea[1] < this .image.height-top?newFillArea[1]: this .image.height-top; |
38 |
canvas.drawImage( this .image, left, top, width, height, newPosition[0], newPosition[1], width, height); |
39 |
return [width, height]; |
ApplicationManager.js
/**
ApplicationManager用于管理应用
@class
*/
function ApplicationManager()
{
/**
初始化对象
@return A 对初始化对象的引用
*/
this.startupApplicationManager = function()
{
this.startupGameObject();
this.background3 = new RepeatingGameObject().startupRepeatingGameObject(g_back2, 0, 100, 3, 600, 320, 1);
this.background2 = new RepeatingGameObject().startupRepeatingGameObject(g_back1, 0, 100, 2, 600, 320, 0.75);
this.background = new RepeatingGameObject().startupRepeatingGameObject(g_back0, 0, 0, 1, 600, 320, 0.5);
return this;
}
/**
更新当前对象
@param dt 自上一帧绘制起经过的秒数
@param context 绘制上下文
@param xScroll x轴的全局滚动值
@param yScroll y轴的全局滚动值
*/
this.update = function(/**Number*/ dt, /**CanvasRenderingContext2D*/ context, /**Number*/ xScroll, /**Number*/ yScroll)
{
g_GameObjectManager.xScroll += 50 * dt;
}
}
ApplicationManager.prototype = new GameObject
05 |
function ApplicationManager() |
11 |
this .startupApplicationManager = function () |
13 |
this .startupGameObject(); |
14 |
this .background3 = new RepeatingGameObject().startupRepeatingGameObject(g_back2, 0, 100, 3, 600, 320, 1); |
15 |
this .background2 = new RepeatingGameObject().startupRepeatingGameObject(g_back1, 0, 100, 2, 600, 320, 0.75); |
16 |
this .background = new RepeatingGameObject().startupRepeatingGameObject(g_back0, 0, 0, 1, 600, 320, 0.5); |
27 |
this .update = function ( dt, context, xScroll, yScroll) |
29 |
g_GameObjectManager.xScroll += 50 * dt; |
32 |
ApplicationManager.prototype = new GameObject |
在这里,我们通过ApplicationManager创建了三个RepeatingGameObject类的实例,每个实例分别显示为一个图层,使用z(深度)和scrollFactor值来创造RepeatingGameObject 渐远和渐慢的效果。
最终结果很不错。视差滚动为画布赋予了完美的纵深感,而整个效果只多编写了一个类就实现了。
看一看视差滚动的Demo吧。http://webdemos.sourceforge.net/jsplatformer4/jsplatformer4.html
建议继续学习:
- 《部落冲突》的设计 (阅读:3534)
- Canvas学习教程 : Canvas介绍 (阅读:3167)
- 手机游戏设计初体验 (阅读:3044)
- 游戏多服务器架构的一点想法 (阅读:2860)
- 使用canvas绘制时钟 (阅读:2865)
- 使用JavaScript和Canvas开发游戏 (阅读:2701)
- HTML5 Canvas(画布)教程 (阅读:2620)
- 游戏程序守护进程-Windows版 (阅读:2532)
- 游戏动作感设计初探 (阅读:2449)
- 网络游戏的社会化 (阅读:2336)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习