Reputation: 51
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)
}
Upvotes: 4
Views: 4801
Reputation: 827
Swift 5
Here is a version calculating the abs value:
extension CGPoint {
static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
CGPoint(x: abs(lhs.x - rhs.x),
y: abs(lhs.y - rhs.y))
}
}
Upvotes: -2
Reputation: 2938
Using CGVector
:
extension CGPoint {
static func -(lhs: CGPoint, rhs: CGPoint) -> CGVector {
return CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
}
}
Upvotes: -1
Reputation: 6151
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)
Upvotes: 13