所以我正在创建一个游戏,我只想检测玩家节点和敌人发射的子弹之间的碰撞。因此,我为每个播放器和项目符号设置了适当的参数以及categoryBitMask和contactTestBitMask。
通过实现didBegin和didEnd函数,我想在碰撞开始和结束时执行一些代码。问题是,当我构建并运行项目时,物理子系统会将子弹绕着播放器移动,而不是通过播放器。这是因为isDynamic属性对于播放器,项目符号或两者都设置为true。显然,首先要尝试的是将isDynamic属性设置为false。但是,当我执行此操作时,发生冲突时将没有回调,并且didBegin / didEnd函数不会执行。
有人对如何解决此问题有任何想法吗?
设置玩家和子弹物理机构的代码;以及didBegin函数在下面供您参考
playerNode!.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: playerNode!.size.width/2, height: playerNode!.size.height/2)) //sets the physics body for the player
playerNode!.physicsBody!.isDynamic = false //we dont want the physics to be simulated by the subsystem
playerNode!.physicsBody!.affectedByGravity = false
playerNode!.physicsBody!.pinned = false
playerNode!.physicsBody!.allowsRotation = false
playerNode!.physicsBody!.categoryBitMask = PhysicsCategory.Player
playerNode!.physicsBody!.contactTestBitMask = PhysicsCategory.Bullet
self.bullet?.physicsBody = SKPhysicsBody(circleOfRadius: bullet!.size.width * 0.5)
self.bullet?.physicsBody?.isDynamic = true
self.bullet?.physicsBody?.pinned = false
self.bullet?.physicsBody?.allowsRotation = false
self.bullet?.physicsBody?.affectedByGravity = false
self.bullet?.physicsBody?.categoryBitMask = PhysicsCategory.Bullet
self.bullet?.physicsBody?.contactTestBitMask = PhysicsCategory.Player
func didBegin(_ contact: SKPhysicsContact) {
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if collision == PhysicsCategory.Player | PhysicsCategory.Bullet {
print("There was a collision with the player and a bullet")
}
}
//Defines the physics category for the game
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1
static let Bullet: UInt32 = 0b10
}
答案 0 :(得分:1)
由于您打开了碰撞功能,因此子弹正在“移动”玩家,而不是通过它。默认情况下,所有物理实体都与其他所有物理实体发生碰撞,而默认情况下,物理实体之间没有注册任何接触。
要做的第一件事是关闭玩家与子弹之间的碰撞,反之亦然,同时保持所有其他碰撞不受影响:
playerNode.physicsBody?.collisionBitMask &= ~physicsCategory.bullet
bullet.physicsBody?.collisionBitMask &= ~physicsCategory.player
编辑:我关于碰撞和接触的循序渐进指南: https://stackoverflow.com/a/51041474/1430420
碰撞和接触指南:测试位掩码: https://stackoverflow.com/a/40596890/1430420
操纵位掩码可打开和关闭各个碰撞和接触。 https://stackoverflow.com/a/46495864/1430420