Blog

Blog

PHODAL

melonjs Javascript游戏开发初探

想找一些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

解压完这个文件,我们就可以得到一个简单的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);
    }
});

然而,发现了一些更有意思的事,下一节介绍。看看结果:

图中的文字和粒子系统可以在接下来中看到,敬请期待。

其他

demo: http://geek.phodal.com/

源码: https://github.com/gmszone/geekslove

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签