Blog | Phodal - A Growth Engineerhttp://www.phodal.com/blog/2014-08-07T12:57:52.391780+00:00Blogmelonjs Javascript游戏开发初探2014-08-07T12:33:34+00:002014-08-07T12:57:52.391780+00:00Phodal Huanghttp://www.phodal.com/blog/author/root/http://www.phodal.com/blog/use-melonJS-develop-javascript-game/想找一些Javascript的游戏引擎试试,试着去做个游戏,于是就找到了melonJS。最后也做了一个小demo,放在了github上。
##melonJS
melonJS是一款轻量级的开源免费HTML5 2D游戏引擎。
> melonJS是一个独立的库,拥有许多非常强大的特性,包括兼容所有主流浏览器(Chrome、Safari、Firefox、Opera、IE等)、支持多声道音频、Tween动画效果、转场效果等。并集成了流行的砖块地图格式,开发者可使用Tiled map编辑器轻松设计游戏关卡,从而更专注于游戏功能开发本身。
看上去似乎有点诱人,但是有:
- Tiled map 地图编辑器
- 粒子系统
那么这个过程就变得有意思了,官方的资料中,展示了这个框架如何快速地开发一个游戏。
###melonJS Hello,World
官方给了一个boilerplate,相当于demo,或许者说一个最小的系统。
[https://github.com/melonjs/boilerplate/archive/master.zip](https://github.com/melonjs/boilerplate/archive/master.zip)
解压完这个文件,我们就可以得到一个简单的demo。会显示一些基础的东西,然后我们可以稍微修改一下,加一些背景之类的。
###melonJS 背景
添加背景的话,新建一个ColorLayer,
var colorLayer = new me.ColorLayer("background", "#a4dad2", 0);
me.game.world.addChild(colorLayer);
打开这个对象一看,
me.ColorLayer = me.Renderable.extend({
init: function (name, color, z) {
this.parent(new me.Vector2d(0, 0), Infinity, Infinity);
this.name = name;
this.color = color;
this.z = z;
},
draw : function (context, rect) {
var _alpha = context.globalAlpha;
context.globalAlpha *= this.getOpacity();
context.fillStyle = this.color;
context.fillRect(rect.left, rect.top, rect.width, rect.height);
context.globalAlpha = _alpha;
}
});
主要的就是draw方法。
###melonJS 添加图片
在boilerplate文件夹中,有一个**resource.js**用来管理资源,于是我们添加张图片
{
name: "ScreenGirl",
type:"image",
src: "data/img/screengirl.png"
},
再渲染这张图片
var screenGirl = new me.ImageLayer("ScreenGirl", 262, 607, "ScreenGirl", 13, 1);
me.game.world.addChild(screenGirl);
于是最后我们就得到我们的**play.js**文件,虽然只有那么点功能,即背景色+图片
game.PlayScreen = me.ScreenObject.extend({
onResetEvent: function() {
game.data.score = 0;
var colorLayer = new me.ColorLayer("background", "#a4dad2", 0);
me.game.world.addChild(colorLayer);
var screenGirl = new me.ImageLayer("ScreenGirl", 262, 607, "ScreenGirl", 13, 1);
me.game.world.addChild(screenGirl);
me.game.world.addChild(new me.ImageLayer("bgColor2", 960, 480, "bgColor2", 2, 1));
me.game.world.addChild(new game.TextLogo(me.video.getWidth(), me.video.getHeight()), 4);
this.HUD = new game.HUD.Container();
me.game.world.addChild(this.HUD);
},
onDestroyEvent: function() {
me.game.world.removeChild(this.HUD);
}
});
然而,发现了一些更有意思的事,下一节介绍。看看结果:
<img src="http://www.phodal.com/static/media/uploads/geekslove.png" width="600"/>
图中的文字和粒子系统可以在接下来中看到,敬请期待。
##其他
demo: [http://geek.phodal.com/](http://geek.phodal.com/)
源码: [https://github.com/gmszone/geekslove](https://github.com/gmszone/geekslove)