1

我目前正在构建一个游戏,我想使用Gameplaykit来组织元素。

我发现了 ECS(实体组件系统)的概念,它可以将功能放入小块(称为组件)中,然后可以将其添加到实体中以赋予其功能。

我想将它与SpriteKit结合使用,我的第一个想法当然是创建一个SpriteComponent,但由于我也在使用SpriteKit的物理引擎,我想知道我应该如何制作PhysicsBodyComponent,因为这个组件可以工作将需要直接访问我的 SpriteKit 节点的物理主体,因此它将依赖于 SpriteComponent,但组件相互依赖不是错误的吗?
我该怎么做?

谢谢你。

4

1 回答 1

2

这取决于您希望如何构建组件。就像你说的那样,最好让它们尽可能灵活、可重用和相互独立。

所以我会像你想要的那样创建一个简单的渲染组件。这是我在游戏中使用的。

 import SpriteKit
 import GameplayKit

 /// GK sprite component
 class SpriteComponent: GKComponent {

     // MARK: - Properties

     /// The rendered node
     let node: SKSpriteNode

     // MARK: GKComponent Life Cycle

     /// Init with image
     init(imageNamed: String) {
         node = SKSpriteNode(imageNamed: imageNamed)
     }

     /// Init with texture
     init(texture: SKTexture) {
         node = SKSpriteNode(texture: texture)
     }
 }

在您的实体类中,您照常添加组件

 class Player: GKEntity {

     override init() { // pass in an image name if you need to
        super.init()

        let spriteComponent = SpriteComponent(imageNamed: "Player")
        addComponent(spriteComponent)
     }
 }

比您将实体添加到场景并定位它。将组件添加到实体后,您可以使用 component(ofType: ...) 方法访问其属性,在本例中为节点属性,并对其进行处理。

 class GameScene: SKScene {

     // code to add entity to scene
     ...

     // position entity 
     if let playerNode = player.component(ofType: SpriteComponent.self)?.node {
        playerNode.position = CGPoint(...)
    }

添加精灵组件后,返回您的实体类并添加物理体。

 ... 
 addComponent(spriteComponent)

 // Set physics body
 if let sprite = component(ofType: SpriteComponent.self)?.node { // component for class is an optional and nil until component is added to entity.
      sprite.physicsBody = SKPhysicsBody(...
      sprite.physicsBody?.categoryBitMask = ...
      ...
 }

这样,您的所有实体都可以使用 1 个渲染组件,但它们上有不同的物理体并使用不同的位置。

您可以创建一个物理体组件并将位掩码等以及您希望将其添加到的节点传递给 init 方法。但是我认为这让它变得非常混乱,所以我更喜欢这种方式。

如果您确实需要使组件相互依赖,请记住每个 GKComponent 都有一个您可以使用的实体属性。我会尽量避免这种情况,以使您的组件更加灵活。

  class SomeComponent: GKComponent {

      func test() {
         entity?.component(ofType: SomeOtherComponent.self)?.someMethod() // only works if this component  is added to entity (entity?) and the other component is also added to entity (...self)?.

       }

  class SomeOtherComponent: GKComponent {

      func someMethod() {

      }
  }

如果您需要更多信息,您应该阅读这些文章,它们非常好。

https://www.raywenderlich.com/119959/gameplaykit-tutorial-entity-component-system-agents-goals-behaviors

http://code.tutsplus.com/tutorials/an-introduction-to-gameplaykit-part-1--cms-24483

希望这可以帮助

于 2016-09-07T15:38:41.477 回答