Search code examples
swiftsprite-kitpositiongameplay-kit

Program getting confused between GKAgent2D position and SpriteKit position


I'm using GameplayKit and Swift. In my agent's move component, I'm running agentWillUpdate: but get an error "Cannot invoke initialiser for type 'Float2' with an argument list of type '(CGPoint)'" on the line where position is determined.

MoveComponent: GKAgent2D, GKAgentDelegate {
init(...)
func agentWillUpdate(agent: GKAgent) {

    guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
      return
    }

    position = float2(spriteComponent.node.position)
  } 

The node position is ok (I've tested this with a print). When I CMD-click through 'position' I'm brought to SpriteKit's position property, instead of GKAgent2D's property. When I try to reference property with agent.property, the debugger tells me 'Value of type 'GKAgent' has no member 'position.'

In the next function call, I get the same error as my original one in reverse, "Cannot invoke initialiser for type 'CGPoint' with an argument list of type '(vector_float2)'"

func agentDidUpdate(agent: GKAgent) {
        guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
            return
        }

    spriteComponent.node.position = CGPoint(position)
}

CMD-clicking through the CGPoint(position) brings me to GKAgent2D. It seems the two "positions" are reversed with each other. Any ideas how to correct this?


Solution

  • If you don't want to write the conversion code every time you can use these extensions and then you can keep the code you had in your question.

    extension CGPoint {
      init(_ point: float2) {
        x = CGFloat(point.x)
        y = CGFloat(point.y)
      }
    }
    
    extension float2 {
      init(_ point: CGPoint) {
        self.init(x: Float(point.x), y: Float(point.y))
      }
    }