Bendable arm rotation in SpriteKit - rotate at poi

2019-08-18 18:24发布

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.

enter image description here

This is what it looks like after a -90 degree rotation on the lower arm

enter image description here

How would I simulate the lower arm being connected to the upper arm at the elbow? I've tried multiple SKConstraints but couldn't find one that worked for me properly.

1条回答
ら.Afraid
2楼-- · 2019-08-18 18:29

You want to use an SKPhysicsJointPin

Here are the available Sprite-Kit joints :https://developer.apple.com/reference/spritekit/skphysicsjoint

enter image description here

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:

  1. Create two physics bodies.
  2. Attach the physics bodies to a pair of SKNode objects in the scene.
  3. 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.
  4. Retrieve the scene’s SKPhysicsWorld object.
  5. 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.

查看更多
登录 后发表回答