Phaser 3中自定义函数内Tween无法运行的问题求助
问题分析与解决:自定义函数中Phaser
this 指向错误导致Tween无法运行 错误根源
不是Phaser机制问题,是JavaScript的this绑定规则导致的:
- Phaser的
preload、create等生命周期函数会自动把this绑定到当前场景实例,所以你能通过this.add、this.tweens访问Phaser的API。 - 但直接调用自定义的
Gotween()时,函数内部的this默认指向全局对象(浏览器环境下是window),而window.add不存在,因此抛出Cannot read properties of undefined (reading 'sprite')的错误。
解决方法
以下三种方案任选其一:
方案1:调用时手动绑定this
在create函数中用call方法把场景实例传递给Gotween,强制绑定this指向:
function create () { Gotween.call(this); // 绑定当前场景实例为Gotween的this } function Gotween (){ let back = this.add.sprite(100, 100, 'back') .setInteractive().setScale(0.2); this.tweens.add({ targets: back, x: {value: 100, duration: 1500, ease: 'Power2'}, y: {value: 500, duration: 500, delay: 150} }); }
方案2:使用箭头函数定义Gotween
箭头函数会继承外层作用域的this,所以Gotween里的this会和create里的this保持一致:
function create () { Gotween(); } const Gotween = () => { // 箭头函数继承create的this let back = this.add.sprite(100, 100, 'back') .setInteractive().setScale(0.2); this.tweens.add({ targets: back, x: {value: 100, duration: 1500, ease: 'Power2'}, y: {value: 500, duration: 500, delay: 150} }); }
方案3:将场景实例作为参数传入
直接把场景实例当作参数传递给Gotween,避免依赖this绑定:
function create () { Gotween(this); // 传入当前场景实例 } function Gotween (scene){ // 接收场景实例参数 let back = scene.add.sprite(100, 100, 'back') .setInteractive().setScale(0.2); scene.tweens.add({ targets: back, x: {value: 100, duration: 1500, ease: 'Power2'}, y: {value: 500, duration: 500, delay: 150} }); }
验证
以上三种方案都能让Gotween函数正确访问Phaser的API,Tween可以正常运行。
内容的提问来源于stack exchange,提问作者sefatheking
相关产品推荐
相关产品推荐

