oop - 如何使用内部类创建不同的对象
问题描述
最近在学习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 个不同的对象,这些对象具有不同的颜色、大小、位置和方法,可以使用面向对象的编程分别对大小进行补间。
我该怎么做才能让它发生?我需要一个方向或建议
谢谢
解决方案
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);
推荐阅读
- javascript - Vimeo,检测全屏以阻止获取新播放器(动态宽度更改)
- tensorflow2.0 - 自定义损失函数 TF 2.0 中的 Model.get_weights
- javascript - JS过滤什么是item[key]?
- react-native - 在 setState 和 API 结果之后取消定义数组
- python - 无法创建while无限循环
- continuous-integration - 无人机中的“拉”参数有什么作用?
- jquery - 如何使用 jQuery 向当前 URL 添加 HTML 属性
- reactjs - 如何在 React 中同时获取两个输入字段的值?
- python - Python List 无法将变量识别为整数
- java - 如何判断哪些第三方 Java 库正在使用 Log4j 1.x?