我正在制作一个简单的游戏,它有一根固定在屏幕中间的弹性绳索,还有一个连接到绳子另一端的球。通过在屏幕上移动手指,您可以移动球,并且可以将球向上拉到底部,从而将球向上扔。
到目前为止我的代码看起来像这样:
var ball = SKSpriteNode(imageNamed: "Ball")
override func didMove(to view: SKView) {
var ropeSegments = [SKSpriteNode]()
let ropeHolder = SKSpriteNode(imageNamed: "RopeHolder")
ropeHolder.position = CGPoint(x: frame.midX, y: frame.midY)
ropeSegments.append(ropeHolder)
addChild(ropeHolder)
ropeHolder.physicsBody = SKPhysicsBody(circleOfRadius: ropeHolder.size.width / 2)
ropeHolder.physicsBody?.isDynamic = false
for i in 0..<30 {
let ropeSegment = SKSpriteNode(imageNamed: "RopeTexture")
let offset = ropeSegment.size.height * CGFloat(i + 1)
ropeSegment.position = CGPoint(x: ropeHolder.position.x, y: ropeHolder.position.y - offset)
ropeSegments.append(ropeSegment)
addChild(ropeSegment)
ropeSegment.physicsBody = SKPhysicsBody(rectangleOf: ropeSegment.size)
}
for i in 1..<31 {
let nodeA = ropeSegments[i - 1]
let nodeB = ropeSegments[i]
let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!, anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.midY))
physicsWorld.add(joint)
}
ball.position = CGPoint(x: frame.midX, y: ropeSegments.last!.position.y - ball.size.height / 2)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2)
addChild(ball)
let joint = SKPhysicsJointPin.joint(withBodyA: ropeSegments.last!.physicsBody!, bodyB: ball.physicsBody!, anchor: CGPoint(x: ropeSegments.last!.frame.midX, y: ropeSegments.last!.frame.midY))
physicsWorld.add(joint)
let moveAction = SKAction.move(to: CGPoint(x: frame.midX - 100, y: frame.midY), duration: 0.5)
ball.run(moveAction)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let point = touch.location(in: self)
ball.position = point
}
}
绳索的表现非常类似于现实生活中的绳索,但它根本没有弹性。我能够尽可能多地拉球,但是绳子节点以非常缓慢的方式回到默认状态,所以不可能将球扔到身边。
我尝试使用SKPhysicsJointSpring
代替SKPhysicsJointPin
,但它的行为几乎相同。有什么建议吗?