第一次用到prefab,在飞机游戏内,做了一个敌人的prefab,由一个精灵组件外加一个js脚本组成,本来是想着能复用成多个不一样的敌人,但发现无法修改onload方法中定义的速度属性(this.speed = cc.v2(0, -1);无法修改),properties中定义速度也无法改变,尝试类外定义var _speed,然后定义方法修改这个值去改变速度,但是所有用到这个prefab创建的敌人的速度会一起被改变,现在不知道该怎么办了,难道要为每个敌人都创建一个prefab吗?感觉这样太浪费,方法都一样,就是属性有差别。
代码如下
这是敌人prefab下的js脚本
//敌人速度
var _speed = cc.v2(0, -1);
cc.Class({
extends: cc.Component,
properties: {
},
// use this for initialization
onLoad: function () {
this.speed = cc.v2(0, -1);
},
//替换精灵
replaceSpriteFrame: function(spriteFrameName) {
//替换精灵
var sprite = this.node.getComponent(cc.Sprite);
sprite.spriteFrame = loadRes.getSpriteAtlasFrameRes("role/sp_all", spriteFrameName);
//设置碰撞区域
var boxCollider = this.node.getComponent(cc.BoxCollider);
boxCollider.size.width = this.node.getContentSize().width * 0.8;
boxCollider.size.height = this.node.getContentSize().height * 0.3;
},
//设置速度
setBulletSpeed: function(speed) {
this.speed = speed;
},
update: function() {
var position = cc.pAdd(this.node.getPosition(), this.speed);
if (position.y <= -cc.winSize.height * 0.5 - this.node.getContentSize().height * 0.5) {
cc.log("destroy");
this.node.destroy();
}
else {
this.node.setPosition(position);
}
},
onCollisionEnter: function(other, self) {
this.node.destroy();
},
});
这是创建敌人的类
cc.Class({
extends: cc.Component,
properties: {
enemy: cc.Prefab
},
// use this for initialization
onLoad: function () {
},
//开启敌人产生控制器
startEnemyController: function() {
//控制器属性
this.produceSpeed = 1;
this.node.runAction(cc.sequence(cc.delayTime(enemyDelayTime), cc.callFunc(function() {
//开始出现敌人
this.startProduceEnemy();
}, this)));
},
//开始产生敌人
startProduceEnemy: function() {
//产生敌人
this.schedule(this.produceEnemy.bind(this),this.produceSpeed);
},
//更换敌人控制器
replaceBulletController: function() {
//停止旧的
this.unschedule(this.produceEnemy);
//设置新属性
//开始新的
this.startProduceEnemy();
},
//产生敌人
produceEnemy: function() {
var enemy = cc.instantiate(this.enemy);
var enemyPrefab = enemy.getComponent("enemyPrefab");
var arr = [201, 202];
var index = Math.floor(Math.random() * 2);
var enemyAttriArray = enemyAttri.getAttriByType(arr[index]);
enemyPrefab.replaceSpriteFrame(enemyAttriArray[0]); //图片
enemyPrefab.setBulletSpeed(enemyAttriArray[1]); //速度
enemy.group = "enemy";
var x = Math.random() * 300 - 150;
enemy.setPosition(x, 300);
enemyPrefab.enemyMove();
this.node.addChild(enemy);
},
// called every frame, uncomment this function to activate update callback
update: function (dt) {
},
});
有很多还未封装的临时方法,凑合看吧,产生敌人的类是从发射子弹的类直接粘过来,有很多是我对于子弹变化预留的方法,这里还得修改,不过不影响看现在的问题
