2.x this.node.x无法设置

  • Creator 版本: 2.4

  • 目标平台:

  • 重现方式:

  • 首个报错:

  • 之前哪个版本是正常的:

  • 手机型号:

  • 手机浏览器:

  • 编辑器操作系统:

  • 重现概率:

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
@property
speed = 20;

dir :cc.Vec2[] = [cc.v2(0,0),cc.v2(0,1),cc.v2(1,0),cc.v2(0,-1),cc.v2(-1,0)];


// LIFE-CYCLE CALLBACKS:

onLoad () {
    
}

start () {
}
update(dt){
    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,function(event){
        if (event.keyCode == cc.macro.KEY.w){
            console.log("w");
            this.node.y += this.speed * dt;
        }else if(event.keyCode == cc.macro.KEY.a){
            this.node.x -= this.speed *dt;
        }else if (event.keyCode == cc.macro.KEY.s){
            this.node.y -= this.speed * dt;
        }else if (event.keyCode == cc.macro.KEY.d){
            this.node.x +=this.speed*dt;
        }
    })
}
}

终端报错Uncaught TypeError: Cannot read property ‘y’ of undefined,以前直接访问this.node.y 都可以直接设置。为什么这里报错了呢?

改成:

update(dt){
    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (event) => {
        if (event.keyCode == cc.macro.KEY.w){
            console.log("w");
            this.node.y += this.speed * dt;
        }else if(event.keyCode == cc.macro.KEY.a){
            this.node.x -= this.speed *dt;
        }else if (event.keyCode == cc.macro.KEY.s){
            this.node.y -= this.speed * dt;
        }else if (event.keyCode == cc.macro.KEY.d){
            this.node.x +=this.speed*dt;
        }
    })
}

问题主要是关于「作用域」这方面,js 中「普通函数 function() {}」和「匿名函数 () => {}」的区别了解一下。

皮皮给了答案,我提另外一点:就是最好把代码放到 start 里,初始化一次就行。在 update 里疯狂的 on 事件不太对。update 里就根据 this.speed 去设置 node 的 x y就行

解决了!非常感谢!!!!

您好!我也想请教一下这一点。因为我一开始也是想在start里面使用on事件的。但是一直不成功。我当时的思路是:
@property
speed = 20;

direction: cc.Vec2 = cc.v2(0,0);

start(){
    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,(event)=>{
        if(event.keyCode == cc.macro.KEY.w){
            this.direction = cc.v2(0,1)
        }
    })
}
update(dt){
    this.node.x += this.speed * dt * this.direction.x;
    this.node.y += this.speed *dt * this.direction.y;
}

}

但是一直不成功,后面我发现direction: cc.Vec2 = cc.v2(0,0); 这个在键盘事件结束之后又会让direction变成(0,0),所以update一直不成功。 我的TS基础不是很好,想了很久不知道怎么解决。 请大佬指教!!应该怎么改才能把start里面的键盘信息传到update里面?

前辈你好,我在网上查到:
“箭头函数的this指向箭头函数不绑定this会捕获其所在的上下文的this值,作为自己的this值”,

是否可以理解为,这个this已经不是指代当前的node了? 那么现在在这个代码里面this指代的是什么呀?

一个 Vec2 的 direction 是不够的,你可以这样声明 direction = { up: false, down: false, left: false, right: false },按下对应方向,把对应方向的标识设置为 true,在 update 里做判断

谢谢前辈!在您的指导下成功了!

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。