Contents

customField(evaluationBlock:)

Creates a field node that calculates and applies a custom force to the physics body.

Declaration

class func customField(evaluationBlock block: @escaping  SKFieldForceEvaluator) -> SKFieldNode

Parameters

  • block:

    A custom block to be executed when a physics body is affected by the field. Your block should calculate and return the force to be applied to the body.

Return Value

A new custom field node.

Discussion

The value returned by the custom block is a vector for an impulse force which is applied to the physics body being evaluated for that frame. Only the x and y components of the return value are used by SpriteKit, the z component is ignored.

The values passed into the block by the position and velocity arguments measured in meters: if you need to convert them into points — as used by SpriteKit — multiply the values by 150.

The following code shows how to create a custom field to emulate drag. The block returns the negative of the square root of the velocity of the physics body. This decelerates a physics body passing through the SKFieldNode object’s region.

Listing 1. Creating a custom drag field

let simpleDrag = SKFieldNode.customField {
    (position: vector_float3, velocity: vector_float3, mass: Float, charge: Float, deltaTime: TimeInterval) in
    return vector_float3(-sqrt(abs(velocity.x)) * sign(velocity.x),
                         -sqrt(abs(velocity.y)) * sign(velocity.y),
                         0)
}

See Also

Creating Field Nodes