swift - SKPhysicsContact 主体,无法更改属性

标签 swift sprite-kit skphysicsbody skphysicscontact

我在 didBegin(contact:) 中触发了 SpriteKit 物理接触。我为要移出屏幕的 Dot 对象的实例抓取物理体,但是当我尝试像这样更改其位置时,没有任何反应:

第一种方法

/* In GameScene.swift */

func didBegin(_ contact: SKPhysicsContact) {
    let dotBody: SKPhysicsBody
    if contact.bodyA.categoryBitMask == 0b1 {
        dotBody = contact.bodyB
    } else {
        dotBody = contact.bodyA
    }

    if let dot = dotBody.node as? Dot {
        dot.position.x = 10000
    }
}

但是,如果我改为在我的 Dot 类中调用一个方法,并传入该主体,则位置设置正确:

第二种方法

/* In GameScene.swift */

func didBegin(_ contact: SKPhysicsContact) {
    let dotBody: SKPhysicsBody
    if contact.bodyA.categoryBitMask == 0b1 {
        dotBody = contact.bodyB
    } else {
        dotBody = contact.bodyA
    }

    if let dot = dotBody.node as? Dot {
        dot.move()
    }        
}

这是 Dot 类:

import SpriteKit
class Dot : SKSpriteNode {
    let dotTex = SKTexture(imageNamed: "dot")
    init() {
        super.init(texture: dotTex, color: .clear, size: dotTex.size())
        self.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
        self.physicsBody?.categoryBitMask = 0b1 << 1
        self.physicsBody?.contactTestBitMask = 0b1
    }

    func move() {
        let reset = SKAction.run {
            self.position.x = 10000
        }
        self.run(reset)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

谁能解释为什么第二种方法中的位置变化有效但在我的第一种方法中不起作用?

这是一个 link to the project on Github .

最佳答案

func didBegin(_ contact: SKPhysicsContact) {
  let hitDot = contact.bodyB.node! as! SKSpriteNode
  let hitDot1 = contact.bodyA.node! as! SKSpriteNode
    if hitDot.name? == "dot" || hitDot1.name? == "dot" {
       reset = true
    }        
}

   override func update(_ currentTime: TimeInterval) {
    if reset {
        newDot.position.x = 0
        reset = false
    }
}

我刚刚在这里编辑的代码中可能存在小错误。但希望这能给你这个想法。这应该可以正常工作。

关于swift - SKPhysicsContact 主体,无法更改属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199162/

相关文章:

json - 使用 JSON 的 API 到 TableView

ios - Swift 4 SpriteKit 检测联系人

ios - SKNode "origin"是什么?

ios - Sprite Kit - 如果球正在远离或靠近地面,则由于脉冲和重力检测 Y

sprite-kit - 检查是否没有联系

swift - 将 SKShapeNode 与 UIBezierpath 结合使用时不会进行碰撞检测

ios - 调用中参数 #1 缺少参数

swift - 使用 p 和 g 等字母垂直截断标签中的文本

ios - 立即导出 IPA xCode 7 崩溃

ios - 在 Xcode 6 spritekit 级别编辑器中使用 pdf 作为纹理源