msqar msqar - 5 months ago 20
iOS Question

How do i get the real center of a SKSpriteNode in Swift 2?

I'm trying to figure out the center of my Sprite, i used a soccer ball sprite, changed size to be 120 by 120.
I managed to get the touch location.

The way to get the center should be sprite.origin.x + (sprite.width / 2), but for some reason, the value i'm getting is non sense. Because no matter where i touch the ball, the touch location.x is always smaller than the Sprite center, even though for example I touched on the right side of the ball, so that way location.x should be > than sprite.center.x.

This is the little code to get ball's center point

let ballCenter = CGVectorMake(ball.position.x + (ball.frame.width / 2),
ball.position.y + (ball.frame.height / 2))


But when I print the results like this, is always going to the "true" case.

if location.x < ballCenter.dx {
print("touched on left of ball ", location.x, location.y)
}else{
print("touched on right of ball ", location.x, location.y)
}


This is driving me crazy, can anyone help me to understand this? The sprite origin isn't in the bottom-left?

Also, why the scene frame is so small? I see that my screen Width is 375.0 and screen Height is 667.0 when i'm using an iPhone 6S, shouldn't it be bigger? This is so confusing.

Thanks in advance.

Answer

A SpriteNode's origin is in the center of the sprite by default. If you want to get the center of the node, just use let ballCenter = sprite.position - this will give you a CGPoint to work with. You can then access the x and y coordinates by using ballCenter.x and ballCenter.y.

Also, if you're wanting to create a point like you're currently doing with ballCenter, use CGPointMake() instead of CGVectorMake().