Reputation: 1265
I use ball.frame.intersects(bar.frame)
, where ball = SKShapeNode(circleOfRadius: BALL_RADIUS)
and bar = SKShapeNode(rectOfSize: <Some CGSize object>)
While this works, there is an invisible square in which the circle is inscribed. The diameter of the circle is the same as the side of the square. This square is what ball.frame
is, so sometimes, the ball will act like it's intersecting the bar, but visually it's not.
In this screenshot you can see that the ball is stopped, and therefore the game is over because ball.frame.intersects(bar.frame)
returned true, even though visually the ball isn't even touching the bar.
So how do I check if the ball is really intersecting the bar, and not if the ball's frame is intersecting?
Upvotes: 1
Views: 599
Reputation: 126137
SpriteKit has decently powerful collision detection in its physics subsystem — you don't have to roll your own.
Create SKPhysicsBody
objects for the ball and the bars, using init(circleOfRadius:)
for the former and init(rectangleOfSize:
for the latter.
Then, you can either:
Drive all the movement yourself, and use SKPhysics
only to test for collisions. In this case you need to set your scene's physicsWorld.gravity
to the zero vector, and call allContactedBodies()
on the ball when you want to see if it's contacting a bar.
Let SKPhysics
drive the movement, by setting velocities or applying impulses. In this case you'll need to set a contact delegate for your physics world, and then you'll get a callback whenever a collision occurs.
For more details on either approach, see the docs.
Upvotes: 3
Reputation: 5935
After detecting that ball frame intersects box frame:
Upvotes: 0