我有两个精灵。当一个精灵碰到另一个精灵时,我想检测碰撞,并向其中一个精灵施加动量,然后对其施加重力,使其脱离场景。我已经完成了如下操作:
func didBegin(_ contact: SKPhysicsContact) {
let vectorOrientation = bat.zRotation + 1.57
print("voector orientation is \(vectorOrientation)")
let deg = vectorOrientation * 180 / 3.1415
let xcomponent = cos(deg) * 400
let ycomponent = sin(deg) * 400
if contact.bodyB.node?.name == "redDot" || contact.bodyA.node?.name == "redDot"
{print("contact made!")
// redDot?.physicsBody?.applyImpulse
redDot?.physicsBody?.applyImpulse(CGVector(dx: xcomponent, dy: ycomponent))
redDot?.physicsBody?.affectedByGravity = true
let finish = SKAction.run{
self.gameOver()
}
let delayEnd = SKAction.wait(forDuration: 1)
let delaythenEnd = SKAction.sequence([delayEnd, finish])
self.run(delaythenEnd)
}
精灵实际上确实从屏幕上掉了下来,并对其施加了正确的脉冲。
此后,这是被触发的gameOver函数,其中添加了一个标签:“您输了!”和一个再次播放按钮:
func gameOver() {
let playButton = SKSpriteNode(imageNamed: "playButton")
playButton.name = "play"
playButton.position = CGPoint(x: frame.midX, y: frame.midY - frame.size.height/6)
youLostLabel = SKLabelNode(text: "you lost!")
youLostLabel.position = CGPoint(x: frame.midX, y: frame.midY)
youLostLabel.fontSize = 200
addChild(youLostLabel)
addChild(playButton)
scene?.isPaused = true
}
这也可行。
我编写了一个函数,将掉下场景的精灵放回开始时的位置,消除重力和脉冲,并添加其他精灵。如下:
func resetScene(){
redDot?.physicsBody?.affectedByGravity = false
redDot?.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
redDot?.position = CGPoint(x: 0 , y: 0)
addChild(bat)
}
最后,当播放器按下“播放”按钮时,所有按钮都应该放在一起,红点返回到开始时的位置,场景未暂停,标签和播放按钮消失。我已使用此代码执行此操作:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self))
print(t.location(in: self))
}
let touch = touches.first
if let location = touch?.location(in: self) {
let theNodes = nodes(at: location)
for node in theNodes {
if node.name == "play" {
node.removeFromParent()
youLostLabel.removeFromParent()
bat.removeFromParent()
self.resetScene()
self.scene?.isPaused = false
//addChild(bat)
//self.run(spawnForever)
}
}
}
}
但是可悲的是,当我按下“再次播放”按钮后,红点要么不再出现,要么短暂出现然后掉落,好像它仍然具有相同的冲动和引力,而“你输了!”标签停留在屏幕上(有时它实际上消失了)。
有人知道这里发生了什么吗?
干杯!