DrOverbuild
DrOverbuild

Reputation: 1265

Detecting when a circle really intersects a node

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.

enter image description here

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

Answers (2)

rickster
rickster

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:

  1. 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.

  2. 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

Owen Hartnett
Owen Hartnett

Reputation: 5935

After detecting that ball frame intersects box frame:

  • Determine the radius of the ball
  • Determine the point on the line that is the edge of the ball from the center of the ball to the edge of the box. (Hint: pythagorean theorem - hypotenuse = radius)
  • Is this point inside the box's rect?
  • Repeat for each point in the box.

Upvotes: 0

Related Questions