场景移动
场景向前移动
移动到一定像素后,再回到原位
//不断修改x轴坐标
//获取当前节点x的坐标
var x = this.node.x;
//x + 当前帧该移动的距离
x += this.speed*dt; //运行当前帧的时间
//当前位置小于重置位置,重置x
if(x<=this.resetX){
x -= this.resetX;
}
this.node.x = x;
数据交互
//Globals.js
//全局变量,全局共享
window.Global={
GameManager:null
}
//GameManager.js
var GameManager = cc.Class({
extends: cc.Component,
properties: {
},
//静态变量
statics:{
State
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
//将GameManager类型放入全局数据中
//window.Global.GameManager = GameManager
Global.GameManager = GameManager;
},
start() {
},
// update (dt) {},
});
主角的控制
动画制作
跳跃和下落实现
//控制小羊运动 sheep.js
//枚举
var State = cc.Enum({
None: -1, //静止
Run: -1, //跑
Jump: -1, //t跳
Drop: -1, //落下
DropEnd: -1, //落下结束
Dead: -1 //死亡
})
cc.Class({
extends: cc.Component,
properties: {
state: {
default: State.None,
type: State,
}
},
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
start() {
},
// update (dt) {},
});
设置动作
捕捉事件
当状态发生改变时,播放对应状态下发生的变化
get/set 声明
在属性中设置了 get 或 set 以后,访问属性的时候,就能触发预定义的 get 或 set 方法。定义方法如下:
properties: {
width: {
get: function () {
return this._width;//读取属性
},
set: function (value) {
this._width = value;//设置属性
}
}
}
如果你只定义 get 方法,那相当于属性只读。
来源:官方文档
属性隐藏
//属性前面加下划线默认隐藏
_state: {
default: State.None,
type: State,
//visible:flase
//另外一种隐藏方法
}
实现
//sheep.js
state:{
get:function(){
return this._state
},
set:function(value){
if(value !== this._state){
//说明状态发生改变
this._state = value;
//状态
if(this._state !== State.None){
this.updateAnimation()
}
}
}
}
//根据状态发生变化播放相关动画
updateAnimation(){
//播放动画api
//获取Animation组件上的动画剪辑
var animName = State[this._state];//小羊当前状态
},
小羊动作实现
//sheep.js
update (dt) {
//判断当前状态
switch (this.state) {
case State.Jump:
if(this.currentSpeed<0){
this.state = State.Drop;
}
break;
case State.Drop:
if(this.node.y < this.grounY){
this.node.y = this.grounY;
this.state = State.DropEnd;
}
break;
case State.DropEnd:
this.state = State.Run;
break;
default:
break;
}
var flying = this.state === State.Jump || this.node.y > this.grounY
if(flying){
//重力的影响
this.currentSpeed -= this.gravity * dt;
this.node.y += dt * this.currentSpeed;
}
},
对象池
官方文档
适用于经常创建于销毁的对象,例如管道处理。
//SceneManager.js
//管理所有需要重复利用的节点
cc.Class({
extends: cc.Component,
properties: {
_pool:null
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
Global.senceManager = this;
//实例化对象池
this._pool = new cc.js.Pool(function(obj){
console.log("clear obj success")
},10);
this._pool.get = this.getCompObj;
},
//的到组件上的节点
getCompObj:function(comp){
for(var i=0; i<this.count; i++){
//临时数组,用于存放从池中取出的脚本组件对象
var array = [];
//从节点池中取出一个脚本对象组件
var obj = this._get();
//取出的时候进行判断
if(obj instanceof cino){
//遍历临时数组,将数组中的对象,返还给节点池
array.forEach(function(o){
this.put(o);
})
return obj;
}
array.push(obj);
}
},
start () {
},
// update (dt) {},
});
预制资源创建出节点,绑定到场景中
//尘土动画播放
spawnDust:function(animName){
//动态创建dust
var dust = Global.senceManager.spawn(this.dustPrefab,Dust,this.node);
//设置dust位置
dust.node.position = cc.v2(0,0);
//播放dust上的动画剪辑
dust.playAnim(animName)
},