我有一个用 create-react-app 创建的 React 应用程序,我也在尝试集成 Phaser 3。我关注了 this guide开始。我有 Canvas 渲染文本,但在预加载中加载图像似乎不起作用。我得到默认的无法加载显示的纹理图像。
import ExampleScene from "./scenes/ExampleScene";
import * as React from "react";
export default class Game extends React.Component {
componentDidMount() {
const config = {
type: Phaser.AUTO,
parent: "phaser-example",
width: 800,
height: 600,
scene: [ExampleScene]
};
new Phaser.Game(config);
}
shouldComponentUpdate() {
return false;
}
render() {
return <div id="phaser-game" />;
}
}
示例场景:
import Phaser from "phaser";
export default class ExampleScene extends Phaser.Scene {
preload() {
this.load.image("logo", "assets/logo.png");
}
create() {
const text = this.add.text(250, 250, "Phaser", {
backgroundColor: "white",
color: "blue",
fontSize: 48
});
text.setInteractive({ useHandCursor: true });
this.add.image(400, 300, "logo");
text.on("pointerup", () => {
console.log("Hello!");
//store.dispatch({ type: ACTION_TYPE });
});
}
}
这个想法是创建一个基于简单基因引擎的花朵生长的可视化。因此 Phaser 将从 Store 获取有关当前状态的说明。
我猜这与 Phaser 的加载方式有关,并且与 React 的更新方式存在冲突。我正在阻止组件更新,因为我只需要游戏通过听商店来接收指令
我已经看过这个 SO answer和 accompanying wrapper ,但它已经过时了。
在 Create-React-App 中,如何让 Phaser 加载图像?
代码沙盒:https://codesandbox.io/s/github/nodes777/react-punnett/tree/phaser-game
repo :https://github.com/nodes777/react-punnett/tree/phaser-game
最佳答案
其他选项是使用 网络组件 能够集成移相器 使用任何其他框架(React、Angular、VueJS 等),检查这个 npm 包:https://www.npmjs.com/package/@ion-phaser/core
此外,您可以使用该库的 React 包装器来使用 移相器 轻松使用 React 组件,因此您无需直接操作 WebComponents,例如:
import React from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'
const game = {
width: "100%",
height: "100%",
type: Phaser.AUTO,
scene: {
init: function() {
this.cameras.main.setBackgroundColor('#24252A')
},
create: function() {
this.helloWorld = this.add.text(
this.cameras.main.centerX,
this.cameras.main.centerY,
"Hello World", {
font: "40px Arial",
fill: "#ffffff"
}
);
this.helloWorld.setOrigin(0.5);
},
update: function() {
this.helloWorld.angle += 1;
}
}
}
const App = () => {
return (
<IonPhaser game={game} />
)
}
export default App;
欲了解更多详情,请查看 repo:https://github.com/proyecto26/ion-phaser/tree/master/react
关于reactjs - 如何将 Phaser 集成到 React 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667188/