I am trying to simulate a bendable arm using SpriteKit. I have an upper arm SKShapeNode
and a lower arm SKShapeNode
.
How would I rotate the lower arm so it rotates at the elbow instead of rotating on itself?
Here is my straight arm with the upper arm being tan colored and the lower arm being cyan colored.
This is what it looks like after a -90 degree rotation on the lower arm
How would I simulate the lower arm being connected to the upper arm at the elbow? I've tried multiple SKConstraint
s but couldn't find one that worked for me properly.
You want to use an SKPhysicsJointPin
Here are the available Sprite-Kit joints :https://developer.apple.com/reference/spritekit/skphysicsjoint
You add or remove joints using the physics world. When you create a joint, the points that connect the joint are always specified in the scene’s coordinate system. This may require you to first convert from node coordinates to scene coordinates before creating a joint.
To use a physics joint in your game, follow these steps:
- Create two physics bodies.
- Attach the physics bodies to a pair of SKNode objects in the scene.
- Create a joint object using one of the subclasses listed in the diagram above. If necessary, configure the joint object’s properties to define how the joint should operate.
- Retrieve the scene’s SKPhysicsWorld object.
- Call the physics world’s add(_:) method.
The following code pins two nodes, upperArm
and lowerArm
, together using a 'elbow' implemented via an , SKPhysicsJointPin
joint. We calculate the 'elbow' position by taking the middle of the area where upperArm
and lowerArm
overlap - this is pretty crude and should be improved.
let elbowArea = lowerArm.frame.intersection(upperArm.frame)
let elbowPosition = CGPoint(x: elbowArea.midX, y: elbowArea.midY)
let elbowJoint = SKPhysicsJointPin.joint(withBodyA: upperArm.physicsBody!, bodyB: lowerArm.physicsBody!, anchor: elbowPosition) scene.physicsWorld.add(elbowJoint)
You should also set rotation limits on the pin joint (elbow) via the joint's properties:
var shouldEnableLimits: Bool
A Boolean value that indicates whether the pin joint’s rotation is limited to a specific range of values.
var lowerAngleLimit: CGFloat
The smallest angle allowed for the pin joint, in radians.
var upperAngleLimit: CGFloat
The largest angle allowed for the pin joint, in radians.