微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对Cocos2d-JS程序的简单剖析

当我们创建好一个游戏工程后,引擎自动为我们创建了一个场景文件,即src文件夹下的app.js。这应该是一个典型的构建游戏场景的文件,以后创建自己的游戏场景,代码内容应该与此相似:

//创建一个层(Layer)
var HelloWorldLayer = cc.Layer.extend({
    sprite:null,ctor:function () {
        // 1. super init first
        this._super();
        // 2. add a menu item with "X" image,which is clicked to quit the program
        // ask the window size
        var size = cc.winSize;


        // add a label shows "Hello World"
        // create and initialize a label
        var helloLabel = new cc.LabelTTF("Hello World","Arial",38);
        // position the label on the center of the screen
        helloLabel.x = size.width / 2;
        helloLabel.y = size.height / 2 + 200;
        // add the label as a child to this layer
        this.addChild(helloLabel,5);

        // add "HelloWorld" splash screen"
        this.sprite = new cc.Sprite(res.HelloWorld_png);
        this.sprite.attr({
            x: size.width / 2,y: size.height / 2
        });
        this.addChild(this.sprite,0);

        return true;
    }
});

//创建一个游戏场景(Scene)
var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new HelloWorldLayer();
        this.addChild(layer);
    }
});

以上代码中,创建了一个层(Layer)和一个场景(Scene),然后把层添加到场景中。

方法讲解:

  • cc.Scene.extend:Scene继承方法,重写onEnter方法,并在里面初始化自定义的Layer。并将Layer作为孩子节点添加到Scene上显示
  • cc.Layer.extend:继承Layer,在这个层里面,我们可以添加游戏物体。

名词解释:

1.场景(Scene)

Cocos2d-JS引擎抽象的一个对象,用Cocos2d-JS制作游戏就如同拍电影,事实上所有东西都必须放置到一个场景容器中才能最终被显示出来。游戏中我们通常需要构建不同的场景(至少一个),游戏里关卡、界面的切换其实就是一个一个场景的切换,就像在电影中变换舞台或场地一样。

2.层(Layer

通常包含的是直接在屏幕上呈现的内容,并且可以接受用户的输入事件,包括触摸,加速度计和键盘输入等。每个游戏场景都可以有多个层每一层都有各自负责的任务,比如专门负责背景显示的层,或显示敌人的层,或UI控件的层等等。

原文地址:https://www.jb51.cc/cocos2dx/341057.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐