game.js
cc.Class({ extends: cc.Component, properties: { //老鼠的预设体数组 mousePrefab: [cc.Prefab], //老鼠的位置数组 pointmouse:[cc.Vec2], //锤子的的预设体 default:系统默认值 cc.Prefab预制文件实例 chuziPrefab:{ default:null, type:cc.Prefab } }, spawnNewMouse: function() { //获取0-2的数 var num=Math.floor(Math.random()*3) //cc.instantiate来进行初始化(可以理解为实例化创建) var newMouse=cc.instantiate(this.mousePrefab[num]); // 将新增的节点添加到 Canvas 节点下面 this.node.addChild(newMouse); this.mouse=newMouse; // 为mouse设置一个随机位置 var num1=Math.floor(Math.random()*9) newMouse.setPosition(this.pointmouse[num1]); this.mousepoint=newMouse.getPosition() // 将 Game 组件的实例传入mouse组件 newMouse.getComponent('mouse1').game = this; }, onLoad () { this.counn=0 this.timer=0 this.spawnNewMouse() //单点触摸 cc.eventManager.addListener({ event:cc.EventListener.TOUCH_ONE_BY_ONE, onTouchBegan:this.onTouchBegan.bind(this), onTouchMoved:this.onTouchMoved.bind(this), onTouchEnded:this.onTouchEnded.bind(this), onTouchCancelled:this.onTouchCancelled.bind(this) },this.node); }, onTouchBegan:function(touch,event){ console.log("####################"); var pointPos = touch.getLocation(); //返回指定两个向量之间的距离 var dist = cc.pDistance(this.mousepoint, pointPos); if (dist<100) { this.counn++ console.log("********************",this.counn); //调用("mouse1").onPicked(); this.mouse.getComponent("mouse1").onPicked(); //创建锤子 var newChuizi=cc.instantiate(this.chuziPrefab); this.node.addChild(newChuizi,10); newChuizi.setPosition(cc.p(pointPos.x,pointPos.y-20)); } return true; }, onTouchEnded:function(touch,event){ console.log("onTouchEnded"); }, onTouchMoved:function(touch,event){ console.log("onTouchMoved"); }, onTouchCancelled:function(touch,event){ console.log("onTouchCancelled"); }, start () { }, update (dt) {} });
chuizi.js
cc.Class({ extends: cc.Component, properties: { }, //初始化为timer时间为0 onLoad () { this.timer=0 }, start () { }, update (dt) { if(this.timer>1) { // 然后销毁当前锤子节点 this.node.destroy(); } this.timer+=dt }, });
mouse1.js
cc.Class({
extends: cc.Component,
properties: {
game: {
default: null,
序列化serializable: false
},
},
onPicked: function() {
// 当地鼠被收集时,调用 Game 脚本中的接口,生成一个新的mouse
this.game.spawnNewMouse();
// 然后销毁当前mouse节点
this.node.destroy();
},
onLoad () {
this.timer=0
},
start () {
},
update :function(dt)
{
if(this.timer > 3)
{
this.onPicked()
}
this.timer+=dt;
},
});
事件分发机制