【问题标题】:My code detects collisions with a sprite but doesn't collide? - Swift我的代码检测到与精灵的碰撞但没有碰撞? - 斯威夫特
【发布时间】:2016-06-25 04:54:47
【问题描述】:

这是我的didBeginContact:

  func didBeginContact(contact: SKPhysicsContact) {


    let firstBody = contact.bodyA
    let secondBody = contact.bodyB


    let ballWasContacted = firstBody.categoryBitMask == PhysicsCat.Ball || secondBody.categoryBitMask == PhysicsCat.Ball
    let wallWasContacted = firstBody.categoryBitMask == PhysicsCat.Wall || secondBody.categoryBitMask == PhysicsCat.Wall
    let wallCheckWasContacted = firstBody.categoryBitMask == PhysicsCat.wallSpace || secondBody.categoryBitMask == PhysicsCat.wallSpace
    let scoreWasContacted = firstBody.categoryBitMask == PhysicsCat.Score || secondBody.categoryBitMask == PhysicsCat.Score
    let boundaryWasContacted = firstBody.categoryBitMask == PhysicsCat.Boundaries || secondBody.categoryBitMask == PhysicsCat.Boundaries


    if boundaryWasContacted {

        print("I collided with the boundary.")

        }

这是我的边界精灵节点:

  let boundary = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: 50, height: 150))
    boundary.name = "boundary"
    boundary.position = CGPoint(x: self.frame.width / 1.37, y: self.frame.height / 2)
    boundary.physicsBody = SKPhysicsBody(rectangleOfSize: boundary.size)
    boundary.physicsBody!.categoryBitMask = PhysicsCat.Boundaries
    boundary.physicsBody?.contactTestBitMask = PhysicsCat.Ball
    boundary.physicsBody?.collisionBitMask = PhysicsCat.Ball
    boundary.physicsBody!.dynamic = false
    boundary.physicsBody!.friction = 0
    boundary.physicsBody!.restitution = 1
    boundary.zPosition = 5
    self.addChild(boundary)

最后这是我的球:

  Ball = SKSpriteNode(imageNamed: "Ball")
    Ball.size = CGSize(width: 38, height: 38)
    Ball.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    Ball.physicsBody = SKPhysicsBody(circleOfRadius: Ball.frame.width / 2)
    Ball.physicsBody?.categoryBitMask = PhysicsCat.Ball
    Ball.physicsBody?.collisionBitMask = PhysicsCat.Wall
    Ball.physicsBody?.contactTestBitMask =  PhysicsCat.Wall | PhysicsCat.Score | PhysicsCat.wallSpace | PhysicsCat.Boundaries
    Ball.physicsBody?.affectedByGravity = false
    Ball.physicsBody?.dynamic = true
    Ball.physicsBody!.allowsRotation = true
    Ball.zRotation = CGFloat(M_PI)
    self.addChild(Ball)

当我接触到边界时,它会打印“我与边界碰撞”,但我直接穿过它。我的代码中究竟缺少什么以使球和边界之间发生实际碰撞?

【问题讨论】:

    标签: ios swift sprite-kit collision-detection collision


    【解决方案1】:

    更改您的 didBeginContact 以在联系时执行某些操作。

    这个问题已经被问到,这个线程中的解决方案是在你的 didBeginContact 中应用一个 Impluse。

    目前,您只有一个打印语句发生。 尝试添加此答案中的相关代码。

    https://stackoverflow.com/a/29433778/6407353

    【讨论】:

    • 那做了一些事情。现在,当我与边界发生碰撞时,边界消失了......我希望球只是击中它并反弹一点,而不是让它消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多