您的位置:首页 > 移动开发 > Cocos引擎

对Cocos2d-JS程序的简单剖析

2015-10-21 08:32 363 查看
当我们创建好一个游戏工程后,引擎自动为我们创建了一个场景文件,即
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控件的层等等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: