使用SKPhysicsbody检测碰撞



所以我正在创建一个游戏,我只想检测玩家节点和敌人发射的子弹之间的碰撞。因此,我为每个播放器和子弹设置了正确的参数和categoryBitMask和contactTestBitMask。

通过实现didBegin和didEnd函数,我希望在冲突开始和结束时执行一些代码。问题是,当我构建和运行该项目时,物理子系统会在玩家周围移动子弹,而不是穿过玩家。这是因为isDynamic属性对于播放器、项目符号或两者都设置得太真实。显然,首先要尝试的是将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
}

子弹在玩家周围"移动",而不是穿过玩家,因为你打开了碰撞。默认情况下,所有物理体都会与所有其他物理体碰撞,而默认情况下物理体之间没有注册联系人。

首先要做的是关闭玩家和子弹之间的碰撞,反之亦然,同时不影响所有其他碰撞:

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

最新更新