gpt4 book ai didi

ios - 如何在同类节点之间不发生碰撞

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:16 25 4
gpt4 key购买 nike

我正在尝试制作一款带有玩家方 block 和一些障碍方 block 的游戏。玩家可以与障碍物发生碰撞,但障碍物不应相互碰撞,而应相互“穿过”。我的位掩码有以下枚举:

enum bitMask: UInt32 {
case player = 1
case obstacle = 2
case frame = 4
}

这就是我定义播放器 block 的方式:

let player = SKSpriteNode(imageNamed: "yellow-square")
player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.frame.size)
player.physicsBody!.dynamic = false
player.physicsBody!.categoryBitMask = bitMask.player.rawValue
player.physicsBody!.contactTestBitMask = bitMask.obstacle.rawValue
player.physicsBody!.collisionBitMask = 0
addChild(player)
player.physicsBody!.contactTestBitMask = bitMask.obstacle.rawValue
player.physicsBody!.collisionBitMask = bitMask.frame.rawValue

我的障碍物(在 for 循环中):

let obstacle = SKSpriteNode(imageNamed: "black-square")
obstacle.physicsBody = SKPhysicsBody(texture: obstacle.texture!, size: obstacle.frame.size)
boundaryNode.addChild(obstacle)
obstacle.physicsBody!.applyImpulse(CGVectorMake(-15, -10))
obstacle.physicsBody!.categoryBitMask = bitMask.obstacle.rawValue
obstacle.physicsBody!.contactTestBitMask = bitMask.player.rawValue

还有我的联系方式:

func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch(contactMask) {
case bitMask.player.rawValue | bitMask.obstacle.rawValue:
let yourTimeNode = contact.bodyB.node
yourTimeNode?.physicsBody?.allowsRotation = false

let firstNode = contact.bodyA.node
firstNode?.physicsBody?.allowsRotation = false

print("Collision")
default:
return
}
}

目前每个 block 都相互碰撞,我不知道如何关闭障碍物之间的碰撞并保持障碍物和玩家 block 之间的碰撞。

最佳答案

您的代码中有几处需要更改。首先你应该像这样制作位掩码

struct BitMask {
static let player: UInt32 = 0x1 << 0
static let obstacle: UInt32 = 0x1 << 1
static let frame: UInt32 = 0x1 << 2
}

这样你只需要将最后一个数字增加 1,如果你开始添加更多的位掩码,这会让你的生活更轻松。比你这样调用它

...categoryBitMask = BitMask.obstacle // no need for rawValue

你应该把你的联系方式改成这样

/// Did Begin Contact
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 == BitMask.player) && (secondBody.categoryBitMask == BitMask.obstacle) {
// do your thing
}
}

最后在您的播放器和障碍物代码中,首先在播放器代码中您重复了 2 个值 (contactBitMask/categoryBitMask),因此删除它们。其次,你的障碍物相互碰撞的原因是你没有为你的障碍物设置 collisionBitMask。这使它成为默认值 0xFFFFFFFF,这意味着所有位都已设置并且它将与所有内容交互。要修复它,请将其添加到障碍代码中

 obstacle.physicsBody!.collisionBitMask = BitMask.player

现在障碍物只会与玩家发生碰撞。

关于ios - 如何在同类节点之间不发生碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35181689/

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