Add Physics to the Player

You can move players (and enemies) around the scene in many ways. In Gloop Drop, you used actions. In Val’s Revenge, you’ll use the physics engine to move Val, the main character of the game. But before you can do that, you first have to set up a physics body for the player sprite node.

In Chapter 4, Working with Physics and Collision Detection, you learned the ins and outs of using the physics engine, including how to write code to set up the different physics bodies and properties. Now it’s time to learn how to set up physics using the Scene Editor.

Open the GameScene.sks file and select the player sprite node. Look at the Attributes Inspector and scroll down to the Physics Definition section. Switch the Body Type from None to Bounding Circle. Notice the blue outline around the player sprite (enhanced here, for clarity) and the different options available in the inspector for this physics body as shown in the image.

images/UsingTheSceneEditorToAddPhysics/scene-edit-phy-setup-body.png

For the most part, these settings are a 1:1 match to the properties you can access in code. For example, Dynamic is a match for physicsBody?.isDynamic and Allows Rotation is a match for physicsBody?.allowsRotation.

Also, the blue outline that represents the physics body doesn’t exactly include the entire sprite; that’s okay, though, because it covers enough of the sprite that it won’t make too much of a difference during actual gameplay.

For the player node, you need to make several changes:

Disable (deselect) the Allows Rotation and Affected By Gravity options; you don’t want the player sprite to rotate or fall away into nothingness.

Also, set the Friction, Restitution, Lin. Damping, and Ang. Damping to 0; movement should be smooth and consistent.

Finally, set the Category Mask to 1, the Collision Mask to 0, the Field Mask to 0, and the Contact Mask to 0; you’ll return to some of these settings later, but for now, these will do.

You learned about most of these properties and settings in A Closer Look at Physics Bodies. However, if you’re curious about why the mask values are set to 4294967295—the default value in the Scene Editor—this max value indicates that the physics body will interact with every physics body within the scene.

Setting the Preview Options for the Scene

images/aside-icons/important.png

If you don’t see the blue outline of the physics body in the Scene Editor, check your scene’s preview settings. Select the Scene node in the Scene Graph View, and in the Attributes Inspector, verify that the Show Physics Boundaries option is enabled.

Now that you have the player node’s physics body set up, you’re ready to hook up the on-screen controller.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset