Protocol

SKPhysicsContactDelegate

Methods your app can implement to respond when physics bodies come into contact.

Declaration

@protocol SKPhysicsContactDelegate

Overview

An object that implements the SKPhysicsContactDelegate protocol can respond when two physics bodies with overlapping contactTestBitMask values are in contact with each other in a physics world. To receive contact messages, you set the contactDelegate property of a SKPhysicsWorld object. The delegate is called when a contact starts or ends.

You can use the contact delegate to play a sound or execute game logic, such as increasing a player’s score, when a contact event occurs. The following code shows how to display a shockwave effect when two nodes with the name ball come into contact. The code only creates the effect when the collision impulse is above a specified threshold:

Listing 1

Creating a shockwave effect when objects come into contact

let shockWaveAction: SKAction = {
    let growAndFadeAction = SKAction.group([SKAction.scale(to: 50, duration: 0.5),
                                            SKAction.fadeOut(withDuration: 0.5)])
    
    let sequence = SKAction.sequence([growAndFadeAction,
                                      SKAction.removeFromParent()])
    
    return sequence
}()

func didBegin(_ contact: SKPhysicsContact) {
    if contact.collisionImpulse > 5 &&
        contact.bodyA.node?.name == "ball" &&
        contact.bodyB.node?.name == "ball" {
        
        let shockwave = SKShapeNode(circleOfRadius: 1)

        shockwave.position = contact.contactPoint
        scene.addChild(shockwave)
        
        shockwave.run(shockWaveAction)
    }
}

Topics

Responding to Contact Events

didBeginContact:

Called when two bodies first contact each other.

didEndContact:

Called when the contact ends between two physics bodies.

Relationships

Inherits From

See Also

Simulating Physics

SKPhysicsWorld

An object which encapsulates a scene's physics simulation.

SKPhysicsBody

An object which adds physics simulation to a node.

SKPhysicsContact

A description of the contact between two physics bodies.

SKPhysicsJoint

The abstract superclass for objects that connect physics bodies.

SKPhysicsJointFixed

A joint that fixes two physics bodies together.

SKPhysicsJointLimit

A joint that imposes a maximum distance between two physics bodies, as if they were connected by a rope.

SKPhysicsJointPin

A joint that pins together two physics bodies, allowing independent rotation.

SKPhysicsJointSliding

A joint that allows two physics bodies to slide along an axis.

SKPhysicsJointSpring

A joint that simulates a spring connecting two physics bodies.

SKFieldNode

A node that applies physics effects to a portion of the scene.

SKRegion

A definition of an arbitrary area.

vector_float3

A floating point vector type used to perform physics calculations.