使用Swift和Sprite-Kit,我试图在静态SKSpriteNode(称为“pin”)的位置和用户触摸屏幕的位置之间创建一条具有逼真物理特性的绳索。我这样做是通过添加名为ropeNodes的单个SKSpriteNodes,并将它们与一系列SKPhysicsJointPins链接起来。物理工作正常,但是当我尝试旋转每个单独的部件以使它们正确定向时,ropeNodes不再形成直线,也不会旋转到正确的角度。但是,当我删除SKPhysicsJoints时,旋转按预期用于每个单独的节点。为每个单独的ropeNode移动anchorPoint似乎只会使事情变得更糟。为什么会发生这种情况,我该怎么办呢?提前致谢(:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
dx = pin.position.x - location.x
dy = pin.position.y - location.y
let length = sqrt(pow(dx!, 2) + pow(dy!, 2))
let distanceBetweenRopeNodes = 40
let numberOfPieces = Int(length)/distanceBetweenRopeNodes
var ropeNodes = [SKSpriteNode]()
//adds the pieces to the array and the scene at respective locations
for var index = 0; index < numberOfPieces; ++index{
let point = CGPoint(x: pin.position.x + CGFloat((index) * distanceBetweenRopeNodes) * sin(atan2(dy!, -dx!) + 1.5707), y: pin.position.y + CGFloat((index) * distanceBetweenRopeNodes) * cos(atan2(dy!, -dx!) + 1.5707))
let piece = createRopeNode(point)
piece.runAction(SKAction.rotateByAngle(atan2(-dx!, dy!), duration: 0))
ropeNodes.append(piece)
self.addChild(ropeNodes[index])
}
//Adds an SKPhysicsJointPin between each pair of ropeNodes
self.physicsWorld.addJoint(SKPhysicsJointPin.jointWithBodyA(ropeNodes[0].physicsBody, bodyB: pin.physicsBody, anchor:
CGPoint(x: (ropeNodes[0].position.x + pin.position.x)/2, y: (ropeNodes[0].position.y + pin.position.y)/2)))
for var i = 1; i < ropeNodes.count; ++i{
let nodeA = ropeNodes[i - 1]
let nodeB = ropeNodes[i]
let middlePoint = CGPoint(x: (nodeA.position.x + nodeB.position.x)/2, y: (nodeA.position.y + nodeB.position.y)/2)
let joint = SKPhysicsJointPin.jointWithBodyA(nodeA.physicsBody, bodyB: nodeB.physicsBody, anchor: middlePoint)
self.physicsWorld.addJoint(joint)
}
}
}
func createRopeNode(location: CGPoint) -> SKSpriteNode{
let ropeNode = SKSpriteNode(imageNamed: "RopeTexture")
ropeNode.physicsBody = SKPhysicsBody(rectangleOfSize: ropeNode.size)
ropeNode.physicsBody?.affectedByGravity = false
ropeNode.physicsBody?.collisionBitMask = 0
ropeNode.position = location
ropeNode.name = "RopePiece"
return ropeNode
}
这是当我尝试旋转每个ropeNode
时会发生什么的图像答案 0 :(得分:0)
经过一番思考,我认为将表示节点添加为子节点是一个更好的主意,因为您不需要在单独的数组中跟踪额外的节点。要设置子项的旋转,只需展开父项的旋转,然后添加新的旋转角度:
node.zRotation = -node.parent!.zRotation + newRotation
如果绳索段位于容器SKNode
中,您可以通过
for rope in ropes.children {
if let node = rope.children.first {
let newRotation = ...
node.zRotation = -rope.zRotation + newRotation
}
}