首页 > 解决方案 > 如何使用内部类创建不同的对象

问题描述

最近在学习Phaser 3搭建游戏,使用Typescript编写代码。此外,我正在尝试通过在 Phaser 类中使用面向对象的编程来创建不同的对象。

我写的代码如下:

class DifferentGraphics extends Phaser.Scene {
  constructor() {
    super({
      key: "DifferentGraphics"
    });
  }

  create() {
    class Graphic {
      graphic: Phaser.GameObjects.Graphics;
      graphicAdd() {
        this.graphic.fillRect(100, 100, 200, 200);
        this.graphic.fillStyle(0xffffff);
      }
    }

    let GraphicA = new Graphic();
    GraphicA.graphicAdd();
  }
}

编译器没有显示任何 Typescript 错误,但浏览器在运行代码后显示“Uncaught TypeError: Cannot read property 'fillRect' of undefined”。

我不知道我的代码有什么问题?如果有人可以分享您的想法或解决方案,我将不胜感激。

我想要实现的目标是制作 3 个不同的对象,这些对象具有不同的颜色、大小、位置和方法,可以使用面向对象的编程分别对大小进行补间。

我该怎么做才能让它发生?我需要一个方向或建议

谢谢

标签: oopphaser-framework

解决方案


this.graphic 未初始化

您必须在构造函数中初始化 this.graphic,例如

class Graphic {
    graphic: Phaser.GameObjects.Graphics;

   constructor(scene){
     this.graphic = scene.add.graphics(0,0);
   }

    graphicAdd() {
        this.graphic.fillRect(100, 100, 200, 200);
         this.graphic.fillStyle(0xffffff);
        }

   }

然后let GraphicA = new Graphic(this);


推荐阅读