gpt4 book ai didi

sprite-kit - 如何在击中某些敌人后删除敌人?

转载 作者:行者123 更新时间:2023-12-04 00:03:30 25 4
gpt4 key购买 nike

我试图在两次射击后删除一个敌人。这是我的 didBegin

func didBegin(_ contact: SKPhysicsContact) {

var body1:SKPhysicsBody
var body2:SKPhysicsBody

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
body1 = contact.bodyA
body2 = contact.bodyB
}else{
body1 = contact.bodyB
body2 = contact.bodyA
}


if body1.categoryBitMask == PhysicsCatagory.Bullet && body2.categoryBitMask == PhysicsCatagory.Enemy{
//if the bullet has hit the enemy
if body2.node != nil {
spawnSplatter(spawnPosition: body2.node!.position)
body1.node?.removeFromParent()
body2.node?.removeFromParent()
}

这会在击中一次后删除敌人,有人可以告诉我如何在击中两次后删除敌人吗?

最佳答案

通常,尝试删除 didBegin(_ contact: 的节点这不是一个好主意,因为您可能与节点有多个接触,这些接触在第一次接触后变为 nil,这可能会导致崩溃。

var bulletCounter : Int = 0
var nodesToRemove = [SKNode]()

func didBegin(_ contact: SKPhysicsContact) {
var body1:SKPhysicsBody
var body2:SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
body1 = contact.bodyA
body2 = contact.bodyB
}else{
body1 = contact.bodyB
body2 = contact.bodyA
}
if body1.categoryBitMask == PhysicsCatagory.Bullet && body2.categoryBitMask == PhysicsCatagory.Enemy{
//if the bullet has hit the enemy
bulletCounter += 1
nodesToRemove.append(body1.node!) // remove always the bullet
switch bulletCounter {
case 2:
nodesToRemove.append(body2.node!) // remove enemy
bulletCounter = 0
default:break
}
}
}
override func didFinishUpdate()
{
nodesToRemove.forEach(){$0.removeFromParent()}
nodesToRemove = [SKNode]()
}

如果您有 1 个敌人,此示例可能会很有用。如果你有更多敌人,你可以创建一个 bulletCounter属性到您的敌人类别或存储 bulletCounter SKNode 内的值userData属性:

首先创建字典:

enemy.userData = NSMutableDictionary()
enemy.userData?.setObject(0, forKey: "bulletCounter")

在游戏过程中获取/分配你的值(value):

if let bulletCounter = self.userData?.object(forKey: "bulletCounter") {
var counter = bulletCounter as! Int
counter += 1
self.userData?.setObject(counter, forKey: "bulletCounter" as NSCopying)
}

关于sprite-kit - 如何在击中某些敌人后删除敌人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42322779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com