我在 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)
}
}
谁能解释为什么第二种方法中的位置变化有效但在我的第一种方法中不起作用?
最佳答案
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/