已将SpriteKit节点angularDamping设为0仍存在角阻尼问题
SpriteKit单摆无法持续摆动的解决方法
你的单摆会逐渐减速停止,核心是只处理了角阻尼参数,漏掉了两个关键设置:
- 摆球的**线性阻尼(linearDamping)**默认不为0,会持续消耗摆动的动能
- 物理体默认会进入睡眠状态,系统判定为"静止"后会停止模拟运动
只需要做三处修改就能解决问题:
- 给摆球的物理体设置
linearDamping = 0,消除线性运动的阻尼消耗 - 禁用场景物理世界的
allowsSleeping,避免摆球因静止判定进入睡眠 - 明确设置关节的
shouldEnableLimits = false(默认值为false,显式设置更保险)
修改后的完整代码:
// In viewDidLoad scene = SKScene(size: view.bounds.size) scene.backgroundColor = .white // 禁用物理世界睡眠机制 scene.physicsWorld.allowsSleeping = false let anchor = SKShapeNode(circleOfRadius: 10) anchor.physicsBody = .init(circleOfRadius: 10) anchor.position = .init(x: scene.size.width / 2, y: scene.size.height / 2) anchor.physicsBody!.isDynamic = false anchor.physicsBody!.angularDamping = 0 scene.addChild(anchor) let length: CGFloat = 100 let ball = SKShapeNode(circleOfRadius: 5) ball.physicsBody = .init(circleOfRadius: 5) ball.physicsBody!.angularDamping = 0 // 添加线性阻尼设置,消除动能消耗 ball.physicsBody!.linearDamping = 0 ball.position = .init(x: length, y: 0) anchor.addChild(ball) let jointPath = CGMutablePath() jointPath.move(to: .zero) jointPath.addLine(to: .init(x: length, y: 0)) let joint = SKShapeNode(path: jointPath) joint.strokeColor = .black joint.lineWidth = 5 joint.position = anchor.convert(.zero, to: ball) ball.addChild(joint) let pin = SKPhysicsJointPin.joint( withBodyA: anchor.physicsBody!, bodyB: ball.physicsBody!, anchor: scene.convert(.zero, from: anchor) ) pin.frictionTorque = 0 // 明确禁用关节角度限制 pin.shouldEnableLimits = false scene.physicsWorld.add(pin) let skView = SKView(frame: view.bounds) skView.presentScene(scene) view.addSubview(skView)
修改完成后,单摆就能持续保持摆动状态,不会再逐渐减速停止。
内容的提问来源于stack exchange,提问作者Dyldo42
相关产品推荐
相关产品推荐

