Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't subtract two CGPoint operands in Swift 3 error

Tags:

swift3

I’m developing a game in Swift 3 with SpriteKit.

I’m having some problems with the conditional below.

if (personaje.position - lastTouchLocation).length() < pjPixelsPerSecond * CGFloat(dt){
    velocity = CGPoint.zero
} else {
  moveSprite(sprite: personaje, velocity: velocity)
}

I get the following error:

Binary operator '-' cannot be applied to two 'CGPoint' operands.

How can I subtract these two variables?

And I got:

var personaje = SKSpriteNode(imageNamed: "personajee")
var velocity = CGPoint.zero
var lastTouchLocation = CGPoint.zero
… 

func sceneTouched (touchLocation: CGPoint) {
    lastTouchLocation = touchLocation
    movePjToLocation(location: touchLocation)

}
like image 254
MatVH Avatar asked Oct 17 '25 02:10

MatVH


1 Answers

You have to define by yourself the - operator for CGPoint. Declare the function outside of any class's scope, so it will be visible in your whole project.

// Declare `-` operator overload function
func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint { 
    return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
// TEST
let point1 = CGPoint(x: 10, y: 10)
let point2 = CGPoint(x: 5, y: 5)
print(point1 - point2) //prints (5.0, 5.0)
like image 79
dirtydanee Avatar answered Oct 21 '25 22:10

dirtydanee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!