Search code examples
swift3sprite

How to generate a CGVector with two CGPoint in Swift 3


I'm developing a small game in Swift 3. I want to move my enemies to the character position, I tried to use this function:

let actionTransaction6 = SKAction.move(to: CGPoint(x: 
personaje.position.x, y:personaje.position.y ), duration: 6.0 -  
Double(nivel))

enemigo6.run(actionTransaction6)

But the enemies stop when they arrive at the initial point of my character. I know that there's a function to move to an specific direction, but I wasn't be able to "find" my CGVector. It might be something like this or what?

SKAction.move(by: enemigo6.position - personaje.position, duration: 10)

Thanks for advance!


Solution

  • There is no - operator defined for CGPoint and there is no function to create a CGVector from two points.

    Just create the vector manually from components:

    let movement = CGVector(
        x: enemigo6.x - personaje.position.x,
        y: enemigo6.y - personaje.position.y
    )
    SKAction.move(by: movement, duration: 10)