cc.Class({
extends: cc.Component,
properties: {
flags: {
default: [],
type: [cc.Node],
},
speed: 2,
_currentMove: 0,
_forward: true,
},
// use this for initialization
onLoad: function () {
},
start: function () {
this.node.position = this.flags[0].position;
},
// called every frame, uncomment this function to activate update callback
update: function (dt) {
this.movement();
},
movement: function () {
// comparePos is a custome helper method, check bottom of script
if (this.comparePos(this.node.position, this.flags[this._currentMove].position)
&& this._forward) {
this._currentMove++;
this.moveActions();
}
else if (this.comparePos(this.node.position, this.flags[this._currentMove].position)
&& !this._forward) {
this._currentMove--;
this.moveActions();
}
if (this._currentMove >= this.flags.length - 1) {
this._currentMove = this.flags.length - 1;
this._forward = !this._forward;
}
else if (this._currentMove <= 0) {
this._currentMove = 0;
this._forward = !this._forward;
}
},
moveActions: function () {
var move = cc.moveTo(this.speed, this.flags[this._currentMove].position);
this.node.runAction(move);
},
comparePos: function (a, b) {
return Math.round(a.x) == Math.round(b.x) &&
Math.round(a.y) == Math.round(b.y)
},
});我使用Cocos Creator,基本上我有一个空对象数组,我希望我的敌人在这些对象上来回巡逻。问题是敌人会完成一个完整的回合(向所有物体移动,然后返回),当它返回到第一个对象时会给我一个错误,奇怪的是,有时它会在错误发生之前完成超过1轮:
Uncaught TypeError: Cannot read property 'position' of undefined可能是因为位置比较不够准确,但我不知道怎么做。
更新:我终于修复了它,问题就在这里:
this._forward = !this._forward;我把它改成了这个
this._forward = true; // and false down below这很奇怪,但现在一切都很好。
发布于 2016-03-21 17:12:07
发布于 2016-03-23 08:21:49
要么是这句话:
if (this.comparePos(this.node.position, this.flags[this._currentMove].position)或者这一行:
else if (this.comparePos(this.node.position, this.flags[this._currentMove].position)您的this._currentMove超出了数组大小的范围,或者this.flags[]数组在该位置上没有定义。添加其他日志以获得确切的场景
https://stackoverflow.com/questions/36137016
复制相似问题