【问题标题】:Is there a way to make phaser game object into a react controlled component?有没有办法将移相器游戏对象变成反应控制的组件?
【发布时间】:2020-04-08 05:51:00
【问题描述】:

我正在尝试使用 react 作为游戏的 UI 部分来制作网页游戏,并使用 Phaser 3 作为引擎。我已经集成了移相器并与 ion-phaser/react 反应,如果在运行移相器应用程序时所有数据都在那里,它工作得很好,但是我不知道我是否可以在移相器应用程序运行时将数据提供给它.

例如:

const GameEngine = ({width, backgroundColor}) => {
  const state = { /* ... game config */ };
  let {initialize, game} = state;

  return <IonPhaser game={game} initialize={initialize} />;
};

如果提供了道具宽度和背景,这很有效,但是当它们发生变化时,移相器不会更新。有没有办法从外部不断地在游戏中输入数据?

【问题讨论】:

    标签: reactjs ion phaser


    【解决方案1】:

    一种选择是将事件从 React 发布到 Phaser 的事件系统。如果您已经在 React 组件中引用了 Phaser game 对象,这将非常简单。

    在您的 React 组件中,您可以执行以下操作:

    game.events.emit('MY_EVENT', 'Hello world!')
    

    然后,在任何 Phaser 场景中,您都可以执行以下操作:

    this.game.events.on('MY_EVENT', (event) => {
      console.log(event)
    })
    

    【讨论】:

      【解决方案2】:

      我也在努力解决这个问题。 最终解决了一个hacky的解决方法。 在 React 状态之外定义游戏配置对象,并继续检查游戏配置对象上是否存在实例键。请参阅下面的 getInstance 函数:

      import React from "react";
      import Phaser from "phaser";
      import { IonPhaser } from "@ion-phaser/react";
      
      const game = {
          /* ... game config */ 
      };
      
      function getInstance() {
          if (game.instance) {
          console.log("ready")
          return Promise.resolve(game.instance);
          } else {
          console.log("waiting")
          return new Promise((resolve) => {
              const interval = setInterval(() => {
              if (game.instance) {
                  clearInterval(interval);
                  resolve(game.instance);
              }
              });
          }, 30);
          }
      }
      
      export default class GameEngine extends React.Component {
          constructor(props) {
          super(props);
      
          this.state = {
              isReady: false,
          };
          }
      
          componentDidMount() {
          getInstance().then((instance) => {
              console.log(instance)
              this.setState({ isReady: true });
          });
          }
      
      
          render() {
          const { initialize } = this.props;
          return (
              <IonPhaser
              game={game}
              initialize={initialize}
              />
          );
          }
      }
      

      我在 GitHub ion-phaser 项目上打开了一个问题 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多