gpt4 book ai didi

swift - 为什么我的碰撞/接触在 Swift 中不起作用?

转载 作者:行者123 更新时间:2023-11-30 13:58:03 25 4
gpt4 key购买 nike

我一直在研究新游戏中的接触/碰撞。我刚刚编写了这个代码,但它无法正常工作。这是我的代码:

广场详细信息:

    square.position = CGPointMake(self.size.width/2, self.size.height/1.5)
square.zPosition = 35
square.size = CGSize(width: 40, height: 40)
square.physicsBody = SKPhysicsBody(rectangleOfSize: square.size)
square.physicsBody?.affectedByGravity = false
square.physicsBody?.categoryBitMask = squareGroup
square.physicsBody?.collisionBitMask = obstacleGroup
square.physicsBody?.contactTestBitMask = obstacleGroup

self.addChild(square)

障碍物详细信息(障碍物 1 和 2 相同):

    obstacle1.physicsBody = SKPhysicsBody(rectangleOfSize: obstacle1.size)
obstacle1.physicsBody?.affectedByGravity = false
obstacle1.physicsBody?.dynamic = true
obstacle1.physicsBody?.mass = 10000
obstacle1.physicsBody?.categoryBitMask = obstacleGroup
obstacle1.physicsBody?.collisionBitMask = squareGroup
obstacle1.physicsBody?.contactTestBitMask = squareGroup

这是我的代码,用于他们和类别组之间的联系:

var squareGroup : UInt32 = 0x1 << 0
var obstacleGroup : UInt32 = 0x1 << 1

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
firstBody = contact.bodyA
}



if firstBody.categoryBitMask == 1 && secondBody.categoryBitMask == 2{
let newScene = GameScene(size: self.size)
_ = SKTransition.fadeWithDuration(1)
self.view?.presentScene(newScene)
}
}

如果有人能帮助我那就太好了。在评论中提问。

最佳答案

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

在 else 语句中,您有 firstBody = contact.bodyBfirstBody = contact.bodyA

I think you whanted to write secondBody = contact.bodyA

还添加双重检查联系

if (firstBody.categoryBitMask == 0x1 << 1 && secondBody.categoryBitMask == 2) || (firstBody.categoryBitMask == 0x1 << 2 && secondBody.categoryBitMask == 1){

//enter code here
}

关于swift - 为什么我的碰撞/接触在 Swift 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353842/

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