So, like my SKSpriteNode
s, I am trying to create a function to make me a default physics body.
Here's my DefaultBody.swift
I created:
import Foundation
import SpriteKit
enum Type {
case rectangle
case circle
}
// Create new default physics body
func createPhysicsBodySprite(for body: inout SKSpriteNode, type: Type) {
// Create new physics body
switch type {
case .rectangle:
body.physicsBody = SKPhysicsBody(edgeLoopFrom: body.frame)
case .circle:
body.physicsBody = SKPhysicsBody(circleOfRadius: body.frame.width / 2)
}
body.physicsBody?.isDynamic = false
body.physicsBody?.allowsRotation = false
body.physicsBody?.pinned = false
body.physicsBody?.affectedByGravity = false
body.physicsBody?.friction = 0
body.physicsBody?.restitution = 0
body.physicsBody?.linearDamping = 0
body.physicsBody?.angularDamping = 0
}
func createPhysicsBodyShape(for body: inout SKShapeNode, type: Type) {
// Create new physics body
switch type {
case .rectangle:
body.physicsBody = SKPhysicsBody(edgeLoopFrom: body.frame)
case .circle:
body.physicsBody = SKPhysicsBody(circleOfRadius: body.frame.width / 2)
}
body.physicsBody?.isDynamic = false
body.physicsBody?.allowsRotation = false
body.physicsBody?.pinned = false
body.physicsBody?.affectedByGravity = false
body.physicsBody?.friction = 0
body.physicsBody?.restitution = 0
body.physicsBody?.linearDamping = 0
body.physicsBody?.angularDamping = 0
}
Here I can call the Sprite version easily:
However, although I can do that with an SKSpriteNode
, my SKShapeNode
function does not work, as I get this error:
This does not work, so if I get rid of the inout
in the function and add it as a return, it now works (using the call commented out in the above image)
Is there any reason to this, and how can I use inout
instead of returning the SKShapeNode
?
Note: a PhysicsBody
can be set to an SKShapeNode
Both are var
and not let
as shown here, and so should be mutable: