gpt4 book ai didi

javascript - 在 Phaser3 类方法之间共享变量的最佳方式是什么?

转载 作者:行者123 更新时间:2023-11-30 20:35:49 25 4
gpt4 key购买 nike

我试图找到一种干净、可读的方式来管理 Phaser 类中跨函数的变量,但由于各种原因,我对找到的解决方案不满意。

我知道的是可用的:

全局变量

我不太喜欢这种实现方式,因为其他文件可能会访问变量。

var heroes = [];

var play = new Phaser.Class({
Extends: Phaser.Scene,

initialize: function(){
Phaser.Scene.call(this, {key: 'play'});
},
create: function () {
for(var i = 0; i < 5; i++){
heroes.add(new Hero())
}
},
update: function(){
if(!heroes.length){
heroes.add(new Hero())
}

heroes.forEach(function(hero){
if(hero.hp <= 0){
hero.destroy();
}
});
}
});

DataManager 类(作为注册表实现)

我更喜欢这个,因为它更受控制,但对我来说,DataManager 感觉它是为配置而设计的,而不是作为在类方法之间处理/共享数据的一种方式;此外,访问和更新变量对于获取和设置其值的特定服务来说感觉非常繁琐。

var play = new Phaser.Class({
Extends: Phaser.Scene,

initialize: function(){
this.registry.set('heroes', []);
Phaser.Scene.call(this, {key: 'play'});
},
create: function () {
var heroes = this.registry.get('heroes');

for(var i = 0; i < 5; i++){
heroes.add(new Hero())
}

this.registry.set('heroes', heroes);
},
update: function(){
var heroes = this.registry.get('heroes');

if(!heroes.length){
heroes.add(new Hero())
}

heroes.forEach(function(hero){
if(hero.hp <= 0){
hero.destroy();
}
});

this.registry.set('heroes', heroes);
}
});

使用“这个”

到目前为止,这对我来说是最干净的方式,因为它指的是类对象,并且很容易更新和检索值但是在这种情况下,“this”与一些内部 Phaser 特定变量共享,我想将这些变量分开从。除了命名空间之外,还有其他解决方案吗?

enter image description here

var play = new Phaser.Class({
Extends: Phaser.Scene,

initialize: function(){
this.heroes = [];
Phaser.Scene.call(this, {key: 'play'});
},
create: function () {
for(var i = 0; i < 5; i++){
this.heroes.add(new Hero())
}
},
update: function(){
if(!heroes.length){
this.heroes.add(new Hero())
}

this.heroes.forEach(function(hero){
if(hero.hp <= 0){
hero.destroy();
}
});
}
});

最佳答案

尝试在场景之间传递一些全局数据,发现如下。每个场景都有自己的全局注册表引用。这是文档中的引述:

This is a game-wide instance of the Data Manager, allowing you to exchange data between Scenes via a universal and shared point.
In the default set-up you can access this from within a Scene via the this.registry property.

https://photonstorm.github.io/phaser3-docs/Phaser.Data.DataManager.html这是包含该类详细描述的文档。最近在玩游戏试了一下,用起来很方便。

关于javascript - 在 Phaser3 类方法之间共享变量的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com