gpt4 book ai didi

ios - 在 Swift 2 中检测物理接触

转载 作者:行者123 更新时间:2023-11-29 01:23:18 27 4
gpt4 key购买 nike

我想在我的应用程序中检测两个对象之间的接触。我有一个 enum 来定义不同的类型:

enum ColliderType: UInt32 {

case Ball = 0b010
case Object = 0b001
case Gap = 0b100

}

我还在我的 SKView 中添加了 SKPhysicsContactDelegate:

didMoveToView中,我有

self.physicsWorld.contactDelegate = self

这是我定义的对象

ball = SKSpriteNode(texture: ballTexture)
ball.position = CGPoint(x: CGRectGetMidX(self.frame) - self.frame.width/12, y: self.frame.size.height - (self.frame.size.height - 100))
ball.physicsBody = SKPhysicsBody(circleOfRadius: ballTexture.size().height)
ball.physicsBody!.dynamic = false
ball.physicsBody?.allowsRotation = false
ball.physicsBody!.categoryBitMask = ColliderType.Ball.rawValue
ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ball.physicsBody!.collisionBitMask = ColliderType.Object.rawValue


let boxTexture = SKTexture(imageNamed: "Obstacle.png")
let box1 = SKSpriteNode(texture: boxTexture)
box1.size = CGSizeMake(self.frame.width/4, self.frame.width/8)
box1.runAction(moveAndRemoveBoxes)
box1.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
box1.physicsBody!.dynamic = false
box1.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
box1.physicsBody!.collisionBitMask = ColliderType.Object.rawValue

let gap = SKSpriteNode()
gap.size = box1.size
gap.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
gap.physicsBody!.dynamic = false
gap.physicsBody!.categoryBitMask = ColliderType.Gap.rawValue
gap.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
gap.physicsBody!.collisionBitMask = ColliderType.Gap.rawValue

didBeginContact 函数中,我有:

func didBeginContact(contact: SKPhysicsContact) {

if contact.bodyA.categoryBitMask == ColliderType.Gap.rawValue || contact.bodyB.categoryBitMask == ColliderType.Gap.rawValue {

print("score")
score++

scoreLabel.text = String(score)

} else {

if gameOver == false {

gameOver = true

self.speed = 0


}

}
}

如果你点击屏幕,球对象会从屏幕的一半跳到另一半,并且名为 box1 的对象“掉落”在屏幕的一半上,并通过“看不见的”间隙来检测玩家是否在没有碰撞的情况下通过盒子在屏幕的另一半。所以我想检测球是否触及间隙,以便玩家得分,否则球与盒子碰撞

最佳答案

这是因为您的障碍 contactTestBitMask 正在寻找 Object,而不是 Ball。你想要这个:box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue

鉴于新的变化:

ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue | ColliderType.Gap.rawValue

如果你想让触点起作用,你需要检查间隙值

关于ios - 在 Swift 2 中检测物理接触,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340930/

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