【问题标题】:Entity Component System with Component prototypes具有组件原型的实体组件系统
【发布时间】:2019-05-03 12:05:27
【问题描述】:

我有一个用 ES7 编写的实体组件系统。我想尽量减少它的内存使用。因为系统中的许多实体非常相似,所以它们共享对“相同”组件的引用。我称它们为组件原型

但是有一个问题。我希望能够更改一个实体的组件数据,而不影响其他实体。

它们共享对组件对象的相同引用。我了解,当我想对共享组件进行更改时,我必须制作数据副本并将组件引用更改为该副本,但我想自动执行此操作。

class Entity {
 // get component // prop getter - read from reference
 // set component // clone the data
}

class Component {
   data = 'test'
}

let component = new Components()

let entity1 = new Entity()
let entity2 = new Entity()

entity1.component = component
entity2.component = component // shared entity

entity2.component.data = 'test2' // now the entity should clone the component

任何想法如何实现这一目标?感谢您的任何提示。

【问题讨论】:

    标签: javascript components entity ecmascript-2017


    【解决方案1】:

    我认为你可以在设置真正的对象之前返回一个 defaultComponent 对象

    const defaultComponent = {
    	foo: 'bar',
      x: 1,
      y: 1
    }
    
    class Test {
    	get component() {
      	return this._component || defaultComponent
      }
      set component(c) {
      	this._component = c
      }
    }
    
    const a = new Test()
    console.log(a.component)
    a.component = { ...defaultComponent }
    a.component.x = 3
    a.component.foo = 'derp'
    console.log(a.component)

    但是你觉得这样的优化真的值得吗?

    【讨论】:

      【解决方案2】:

      您可以利用 JavaScript 的原型继承,用继承对象替换现有组件,如下所示:

      entity2.component = Object.create(component) // extend the base prototype
      entity2.component.data = 'test2' // other components don't inherit this change
      

      但请注意,由于您使用的是类(它是原型继承上的某种“自以为是”的语法糖),因此此方法可能会与您现有的代码以奇怪的方式进行交互。

      【讨论】:

        猜你喜欢
        • 2021-02-20
        • 2018-01-05
        • 2018-08-13
        • 2016-01-23
        • 2014-07-06
        • 2018-08-17
        • 2020-05-24
        • 2020-10-18
        • 2016-11-05
        相关资源
        最近更新 更多