Bendable arm rotation in SpriteKit - rotate at point

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

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 SKConstraints but couldn't find one that worked for me properly.

回答1:

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:

  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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!