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:
First, to pass an inout parameter, you must add &
:
createPhyscisBodyShape(for: &topBar, type: .rectangle)
You did this with the &ball
. I wonder why you forgot the &
the second time.
Anyway, you don't need inout
in the first place. SKSpriteNode
and SKShapeNode
are classes. That means as long as you don't set body
to something else with an assignment statement, the changes you made to body
will be reflected in the parameter you passed.
Remove the inout and it should work fine.