An object which adds physics simulation to a node.
- iOS 7.0+
- macOS 10.9+
- tvOS 9.0+
- watchOS 3.0+
SKPhysics object to the
physics property of the
SKNode object to add physics simulation to the node. When a scene processes a new frame, it performs physics calculations on physics bodies attached to nodes in the scene. These calculations include gravity, friction, and collisions with other bodies. You can also apply your own forces and impulses to a body. After the scene completes these calculations, it updates the positions and orientations of the node objects.
SpriteKit supports two kinds of physics bodies, volume-based bodies and edge-based bodies. When you create a physics body, its kind, size, and shape are determined by the constructor method you call. An edge-based body does not have mass or volume and is unaffected by forces or impulses in the system. Edge-based bodies are used to represent volume-less boundaries or hollow spaces in your physics simulation. In contrast, volume-based bodies are used to represent objects with mass and volume. The
is property controls whether a volume-based body is affected by gravity, friction, collisions with other objects, and forces or impulses you directly apply to the object.
SKPhysics class defines the physical characteristics for the body when it is simulated by the scene. For volume-based bodies, the most important property is the
mass property. A volume-based body is assumed to have a uniform density. You can either set the
mass property directly, or you can set the body’s
density property and let the physics body calculate its own mass. All values in Sprite Kit are specified using the International System of Units (SI units). The actual forces and mass values are not important so long as your game uses consistent values.
When you design a game that uses physics, you define the different categories of physics objects that appear in the scene. You define up to 32 different categories of physics bodies, and a body can be assigned to as many of these categories as you want. In addition to declaring its own categories, a physics body also declares which categories of bodies it interacts with. See Working with Collisions and Contacts. You use a similar mechanism to declare which physics field nodes (
SKField) can affect the physics body.
For a volume-based body, you can dynamically control how the body is affected by forces or collisions. See Defining How Forces Affect a Physics Body.
All Physics is Simulated on Physics Bodies
SKPhysics object defines the shape and simulation parameters for a physics body in the system. When the scene simulates physics, it performs the calculations for all physics bodies connected to the scene tree. So, you create an
SKPhysics object, configure its properties, and then assign it to a node’s
There are three kinds of physics bodies:
A dynamic volume simulates a physical object with volume and mass that can be affected by forces and collisions in the system. Use dynamic volumes to represent items in the scene that need to move around and collide with each other.
A static volume is similar to a dynamic volume, but its velocity is ignored and it is unaffected by forces or collisions. However, because it still has volume, other objects can bounce off it or interact with it. Use static volumes to represent items that take up space in the scene, but that should not be moved by the simulation. For example, you might use static volumes to represent the walls of a maze. While it is useful to think of static and dynamic volumes as distinct entities, in practice these are two different modes you can apply to any volume-based physics body. This can be useful because you can selectively enable or disable effects for a body.
An edge is a static volume-less body. Edges are never moved by the simulation and their mass doesn’t matter. Edges are used to represent negative space within a scene (such as a hollow spot inside another entity) or an uncrossable, invisibly thin boundary. For example, edges are frequently used to represent the boundaries of your scene. The main difference between a edge and a volume is that an edge permits movement inside its own boundaries, while a volume is considered a solid object. If edges are moved through other means, they only interact with volumes, not with other edges.
The shape of a physics body affects performance. A circular physics body offers the best performance and can be significantly faster than other physics bodies. If your simulation contains many physics bodies, circular bodies are the best solution. Rectangular then polygonal shapes improve collision accuracy with reduced speed. Physics bodies created from the alpha channel of a texture offer the best fidelity at the expense of highest computational cost.
Creating Physics Bodies
A physics body is created by calling one of the
SKPhysics class methods. Each class method defines whether a volume-based or edge-based body is being created and what shape it has.
Creating and Assigning Physics Bodies
As soon as a node has its physics body set and is added to a scene, it begins to participate in the physics simulation. The following code shows how to create a simple scene containing a shape node that is the curvy ground and a sprite node — the elephant. The shape node’s physics body is created from its path and the sprite node’s physics body is created from the texture automatically generated by SpriteKit when the node was initialized. Because the ground node has its
is set to false, it is not affected by gravity and remains stationary.
After running for a few moments, the above code creates a scene that looks like the illustration in Figure 1 — the sprite node has come to rest in one of the valleys of the curvy ground line:
Use a Physics Shape That Matches the Graphical Representation
In most cases, a physics body should have a size and shape that closely approximates the visual representation of the corresponding node. For example, in Figure 2, the rocket has a narrow shape that is not well represented by either a circle or a rectangle. A convex polygon shape is chosen and fitted to match the sprite’s artwork.
If you do not want to create your own shapes, you can use SpriteKit to create a shape for you based on the sprite’s texture.
When choosing a shape for your physics body, do not be overly precise. More complex shapes require more work to be properly simulated. For volume-based bodies, use the following guidelines:
A circle is the most efficient shape (
A path-based polygon is the least efficient shape, and the computational work scales with the complexity of the polygon (
An edge-based body is more expensive to compute than a volume-based body. This is because the bodies it interacts with can potentially be on either side of an open edge or on the inside or outside of a closed shape. Use these guidelines:
Creating an Edge Loop Around the Scene
The following shows code that is used frequently in games that do not need to scroll the content. In this case, the game wants physics bodies that hit the borders of the scene to bounce back into the gameplay area:
Configuring the Physical Properties of a Physics Body
SKPhysics class defines properties that determine how the physics body is simulated. These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. In most cases, the properties are used to simulate physical effects.
Each individual body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. Here are the most important properties:
massproperty determines how forces affect the body, as well as how much momentum the body has when it is involved in a collision.
frictionproperty determines the roughness of the body’s surface. It is used to calculate the frictional force that a body applies to other bodies moving along its surface.
restitutionproperty determines how much energy a body maintains during a collision—its bounciness.
Other properties are used to determine how the simulation is performed on the body itself:
isproperty determines whether the body is simulated by the physics subsystem.
affectedproperty determines whether the simulation exerts a gravitational force on the body. For more information on the physics world, see Configuring the Physics World.
allowsproperty determines whether forces can impart angular velocity on the body.
Mass Determines a Body’s Resistance to Acceleration
You should set the mass on every volume-based body in your scene so that it properly reacts to forces applied to it.
A physics body’s
density properties are all interrelated. When you first create a body, the body’s area is calculated, and never changes afterwards. The other two properties change values at the same time, based on the following formula:
mass = density x area
When you configure a physics body, you have two options:
• Set the
mass property of the body. The
density property is then automatically recalculated. This approach is most useful when you want to precisely control each body’s mass.
• Set the
density property of the body. The
mass property is then automatically recalculated. This approach is most useful when you have a collection of similar bodies created with different sizes. For example, if your physics bodies were used to simulate asteroids, you might give all asteroids the same density, and then set an appropriate bounding polygon for each. Each body automatically computes an appropriate mass based on its size on the screen.
When to Adjust a Body’s Properties
Most often, you configure a physics body once and then never change it. For example, the mass of a body is unlikely to change during play. However, you are not restricted from doing so. Some kinds of games may require the ability to adjust a body’s properties even while the simulation is executing. Here are a few examples of when you might do so:
In a realistic rocket simulation, the rocket expends fuel to apply thrust. As fuel is used up, the mass of the rocket changes. To implement this in SpriteKit, you might create a rocket class that includes a fuel property. When the rocket thrusts, the fuel is reduced and the corresponding body’s mass is recalculated.
The damping properties are usually based on the body’s characteristics and the medium it is traveling through. For example, a vacuum applies no damping forces, and water applies more damping forces than air. If your game simulates multiple environments and bodies can move between those environments, your game can update a body’s damping properties whenever it enters a new environment.
Typically, you make these changes as part of scene pre- and post-processing using the
Rotating Physics Bodies
A common task in a physics is to pin bodies together. Pinning locks the position of an object but allows it to rotate - for example fixing a wheel to a vehicle. SpriteKit offers two options for pinning physics bodies — either using the
pinned property or creating an
The following code shows how you can implement the simpler method: using the
pinned property. The code creates a sprite node with an image of a pendulum (two circles of different sizes joined by a center rod). A physics body is created based on the generated texture, has its
pinned set to
true, and assigned to the node. The node is rotated 90 degrees — to align horizontally — so that gravity pulls the heavier end towards the ground.
Since the node’s physics body is pinned, it stays in position but rotates around its center.
The following code shows how you create a similar scene, but using a physics joint. In this example, a static anchor is created and added to the scene. The sprite node is added as a child of the anchor node and a
SKPhysics joins the two together:
The resulting scenes behave identically.
The advantage of the first approach is simplicity: it requires less code and, if you don’t need to limit or control the speed of the rotation is the preferred solution. However, using a physics joint offers more functionality: you have control over the anchor point, you can limit the rotation angles with
upper, and you can define the rotation speed with
rotation. If you wish to simulate friction, the physics body’s
angular property is analogous to the joint’s
Other Related Physics Classes
You can use fields to apply forces to a set of physics bodies or to change their velocities. See
You can connect physics bodies together using joints. See