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)
},
});
I'm using Cocos Creator, basically I have an array of empty objects, and I want my enemy to patrol back and forth towards those objects. The problem is the enemy would complete a full round ( move towards all objects and back) and then gives me error when it goes back to the first object, strangely enough, sometimes it will complete more than 1 round before giving the error:
Uncaught TypeError: Cannot read property 'position' of undefined
It might be because the position comparison is not accurate enough, but I don't know how else to do it.
Update: I finally fixed it, the problem was here:
this._forward = !this._forward;
I changed it to this:
this._forward = true; // and false down below
That's very very strange, but it's now working fine :/