Search code examples
macossprite-kitskspritenodeswift5

How to create a CGVector that "points" from one point (CGPoint) to another point


I want to use a CGVector for a SKAction.move, which moves one SKSpriteNode towards another SKSpriteNode.

I want to use this code:

let point: CGPoint = CGPoint(x: CGFloat(arc4random_uniform(UInt32(size.width))), y: CGFloat(arc4random_uniform(UInt32(size.height))))
let object: SKSpriteNode = SKSpriteNode(color: NSColor.red, size: CGSize(width: 10, height: 10))
object.position = CGPoint(x: 50, y: 50)
addChild(object)
object.run(SKAction.move(by: CGVector(), duration: 2.5)) // <- Vector from `object.position` to `point`

Solution

  • You need to use vector math so looking at your code you want to use something like this:

    let P1 = point
    let P2 = object.position
    //Find offset
    let offset = P1 - P2
    //Set X and Y distance to move
    let distX = CGFloat(offset.x)
    let distY = CGFloat(offset.y)
    //set vector
    let vec = CGVector(dx: distX, dy: distY)
    //Set action
    object.run(SKAction.move(by: vec, duration: 2.4)
    

    Let me know how you get on