首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >敌人巡逻系统

敌人巡逻系统
EN

Stack Overflow用户
提问于 2016-03-21 16:48:09
回答 2查看 162关注 0票数 0
代码语言:javascript
复制
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轮:

代码语言:javascript
复制
Uncaught TypeError: Cannot read property 'position' of undefined

可能是因为位置比较不够准确,但我不知道怎么做。

更新:我终于修复了它,问题就在这里:

代码语言:javascript
复制
this._forward = !this._forward;

我把它改成了这个

代码语言:javascript
复制
this._forward = true; // and false down below

这很奇怪,但现在一切都很好。

EN

回答 2

Stack Overflow用户

发布于 2016-03-21 17:12:07

这似乎是一个JavaScript问题。见herehere

根据一个答案,这种情况发生在以下情况:

-The对象具有该属性,且其值不是未定义的。

-The对象具有该属性,其值未定义。

-The对象没有该属性。

(我不知道JS,所以我无法在代码中告诉您到底是什么原因造成了这种情况)。

票数 0
EN

Stack Overflow用户

发布于 2016-03-23 08:21:49

要么是这句话:

代码语言:javascript
复制
          if (this.comparePos(this.node.position,  this.flags[this._currentMove].position)

或者这一行:

代码语言:javascript
复制
  else if (this.comparePos(this.node.position, this.flags[this._currentMove].position)

您的this._currentMove超出了数组大小的范围,或者this.flags[]数组在该位置上没有定义。添加其他日志以获得确切的场景

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36137016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档