xcode - 船舶与硬币相撞无法正常工作

标签 xcode swift

我创建了一个游戏,玩家必须收集硬币。现在,由于某种原因,当屏幕上有很多硬币可供抓取时,当船与硬币相撞时,它将直接穿过与其碰撞的当前硬币,并移除添加到屏幕上的最后一个硬币。我怎样才能使发生碰撞的实际硬币从屏幕上移除?

func didBeginContact(contact: SKPhysicsContact) {
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }


    if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(obstacleCategory)) != 0 {
        ship.removeFromParent()
        let reveal = SKTransition.flipHorizontalWithDuration(0.5)
        let scene = GameOverScene(size: self.size)
        self.view?.presentScene(scene, transition: reveal)
    }

    if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(coinCategory)) != 0 {
        coin.removeFromParent()
        playerScore = playerScore + 1
        playerScoreUpdate()
    }


override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
    if currentTime - self.lastMissileAdded > 1 {
        self.lastMissileAdded = currentTime + 1
        self.addMissile()
    }

    // Current time + 6 takes longer to respawn coins
    if currentTime - self.lastCoinAdded > 1 {
        self.lastCoinAdded = currentTime + 0
        self.addCoin()
    }

    // Current time + 6 takes longer to respawn coins
    //if currentTime - self.lastDiamondAdded > 1 {
      //  self.lastDiamondAdded = currentTime + 1
        //self.addDiamond()
    //}

    self.moveBackground()
    self.moveObstacle()
    self.moveCoin()
    //self.moveDiamond()

}

最佳答案

要移除与 ship 碰撞的 coin,请更改 didBeginContact 函数中第二个条件中的代码。您必须删除属于 secondBody 的节点。在您的代码中,您只需删除一个coin 全局变量。这就是为什么当场景中有其他硬币时它不起作用。

if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(coinCategory)) != 0 {
    secondBody.node?.removeFromParent() // Changed line.
    playerScore = playerScore + 1
    playerScoreUpdate()
}

关于xcode - 船舶与硬币相撞无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976623/

相关文章:

ios - 表格 View 使用 Firestore 在 iOS Swift 中显示重复数据?

iPhone 应用程序在发布版本中中断,而不是在调试版本中中断

xcode - 如何删除我不再关联的团队?

swift - 如何从 userNotificationCenter 中读取内容 - Swift

iphone - 如何在 iOS 上每次打开唯一文件夹中的解压缩文件

swift - 如何计算在 iOS 的 CollectionView 中调用 indexpath 的次数?

Swift:检查编译器是否支持条件一致性

ios - 在 iOS11 中更改 UISearchBar 背景图片

ios - 无法上传嵌入了内部动态框架的IPA

ios - UIFont 为自定义字体返回 nil