问题
I've created 2 SKSpriteNodes, and connected them by a SKPhysicsJointFixed, to keep them stuck together. The problem is when I apply a SKAction.move(by:, duration:)
to the first, it moves alone. why is that, and how can I move them together? I've searched a lot, but can't seem to find any new or useful information. Please help. Thanks in advance.
Here's the code:
import SpriteKit
class myGame: SKScene {
var node1: SKSpriteNode!
var node2: SKSpriteNode!
func createNode(_ position: CGPoint, color: UIColor) -> SKSpriteNode {
let node = SKSpriteNode(color: color, size: CGSize(width: 50, height: 50))
node.position = position
node.physicsBody = SKPhysicsBody(rectangleOf: node.size, center: position)
node.physicsBody?.affectedByGravity = false
node.physicsBody?.allowsRotation = false
return node
}
func setup() {
node1 = createNode(.zero, color: .red)
node2 = createNode(CGPoint(x: 0, y: -50), color: .green)
self.addChild(node1)
self.addChild(node2)
let anchor = CGPoint(x: node1.size.width/2, y: -node1.size.height/2)
let joint = SKPhysicsJointFixed.joint(withBodyA: node1.physicsBody!, bodyB: node2.physicsBody!, anchor: anchor)
physicsWorld.add(joint)
}
override func didMove(to view: SKView) {
setup()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
node1.run(SKAction.move(by: CGVector(dx: 0, dy: 100), duration: 2))
}
}
回答1:
This is very strange indeed, but I have encountered similar things before. Its the AllowRotation on the physicsBody that creates the problem.
fix:
node.physicsBody?.allowsRotation = true
Note: your physics body for the second node is a bit off. I suggest you do like this instead:
node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
And your joint is currently in the right corner of the nodes, Fix:
let anchor = CGPoint(x: 0, y: -node1.size.height/2)
unless you want it to be like that ofc :)
One last tip if you don't already know it. set showPhysics in your gameViewController to see an outline of your physics bodies. it does help a lot when working with physics.
view.showsPhysics = true
来源:https://stackoverflow.com/questions/45174110/skphysicsjointfixed-doesnt-keep-nodes-together-while-moving-one