I'm building a game with balls bouncing within the iPad's screen. Similar to a Pong game. I see that SKScene's SKPhysicsWorld has gravity property, and also controls how objects collide with each other.
Is there some way I can automatically detect if a sprite's edge has collided with the screen's edge, so it can bounce off that? Or do I need to write my own collision code?
You don't need to write much code to make the ball bounce off the edge of the screen. the physics environment can handle all of the above, you just need to instantiate the sprites in the correct way.
First, you will have to set the physicsBody of the scene as such:
In your scene's .h file create two bitmask categories:
And give the scene's physics body a category:
Then create your sprite:
Instead of giving the spriteNode a
[SKAction moveTo: duration:]
, apply an impulse to it's physics body.And voila! The ball will be bouncing off the walls with nothing to stop it.
This is what the .h file should look like:
And this is how the .m file should look like: