ios 为什么联系人在SpriteView中不起作用

lbsnaicq  于 2023-03-20  发布在  iOS
关注(0)|答案(2)|浏览(92)

我试着知道两个精灵什么时候会互相联系,但我无法让它工作。
下面的代码重现了这个问题。我希望当我点击红色方块时,联系人代理方法会触发,但黄色方块到达了它。然而,什么也没发生。代码看起来很长,但实际上很简单。我添加了注解,使它更容易阅读:

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

有人能告诉我我做错了什么吗?
先谢了

qco9c6ql

qco9c6ql1#

如果.isDynamic = false,则didBegin(contact:)不会触发,因此删除这些行并添加physicsWorld.gravity = .zero以防止节点下降。

dm7nw8vv

dm7nw8vv2#

当你使用物理实体时,你应该避免使用动作来移动节点,而应该使用applyForce(_:)applyImpulse(_:)这样的方法,通过设置力和/或冲量来移动实体。
这将允许物理引擎正确地模拟物理交互。

相关问题