我想知道两个精灵何时相互接触,但我无法让它工作。
下面的代码重现了这个问题。我希望当我点击红色方块并且黄色方块到达它时,联系委托方法会触发。但是,没有任何反应。代码看似很多,其实很简单。我添加了评论以使其更易于阅读:
class GameScene: SKScene, SKPhysicsContactDelegate {
private var node: SKSpriteNode!
override func didMove(to view: SKView) {
// Set contact delegate to this class
physicsWorld.contactDelegate = self
// Have the Game Scene be the same size as the View
size = view.frame.size
// Create a yellow square with a volume based physics body that isn't dynamic
node = SKSpriteNode(color: .yellow, size: CGSizeMake(50, 50))
node.position = CGPointMake(100, 100)
node.physicsBody = SKPhysicsBody(rectangleOf: CGSizeMake(50, 50))
node.physicsBody!.isDynamic = false
// Set it's contact bit mask to any value (default category bitmask of
// SKSpriteNode is 0xFFFFFFFF so any value over here would do)
node.physicsBody!.contactTestBitMask = 1
// Add it to the Scene
addChild(node)
// Create a red square with a volume based physics body that isn't dynamic
let otherNode = SKSpriteNode(color: .red, size: CGSizeMake(50, 50))
otherNode.physicsBody = SKPhysicsBody(rectangleOf: CGSizeMake(50, 50))
otherNode.physicsBody!.isDynamic = false
// Set the position to be 100 pts to the right of the yellow square
otherNode.position = CGPointMake(200, 100)
// Add it to the Scene
addChild(otherNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Moves yellow square to where you tapped on the screen
guard let finger = touches.first?.location(in: self) else { return }
node.run(.move(to: finger, duration: 1))
}
func didBegin(_ contact: SKPhysicsContact) {
print("did begin contact")
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Game")
SpriteView(scene: GameScene(), debugOptions: [.showsPhysics, .showsNodeCount])
}
.padding()
}
}
谁能告诉我我做错了什么?
提前致谢
didBegin(contact:)
.isDynamic = false
不会触发所以删除这些行并添加physicsWorld.gravity = .zero
以防止节点掉落。
你还需要
contactTestBitMask = 1
两个节点,而不仅仅是第一个。
当你使用物理体时,你应该避免使用动作移动节点。而是通过设置力和/或脉冲来移动身体,使用像 applyForce(_:) 和 applyImpulse(_:).
这样的方法这样做可能会解决您的问题,但这也会让物理引擎正确模拟物理交互。