gpt4 book ai didi

ios - SKPhysicsJoint 使旋转无法正常工作

转载 作者:行者123 更新时间:2023-11-28 09:00:58 26 4
gpt4 key购买 nike

使用 Swift 和 Sprite-Kit,我试图在名为“pin”的静态 SKSpriteNode 位置与用户触摸屏幕的任何位置之间创建一条具有逼真的物理特性的绳索。我通过添加称为 ropeNodes 的单个 SKSpriteNodes,并将它们与一系列 SKPhysicsJointPins 链接起来来实现这一点。物理效果很好,但是当我尝试旋转每个单独的部分以使它们正确定向时,ropeNodes 不再形成一条直线,也没有旋转到正确的角度。但是,当我删除 SKPhysicsJoints 时,旋转会按预期针对每个单独的节点进行。在每个单独的 ropeNode 的 anchor 周围移动似乎只会让事情变得更糟。为什么会发生这种情况,我该如何解决?提前致谢 (:

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 时发生的情况的图像

enter image description here

最佳答案

经过一番思考,我认为将表示节点添加为子节点是一个更好的主意,因为您不需要在单独的数组中跟踪额外的节点。要设置子项的旋转,只需展开父项的旋转,然后添加新的旋转角度:

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
}
}

关于ios - SKPhysicsJoint 使旋转无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com