简体   繁体   中英

ios swift collision detection

I'm trying to build my first iOS swift game and I have some trouble in detection the collision between objects. I have some objects falling down, and another object on the bottom of the screen. I want to know when the falling objects touches the other object. So, here is what I have:

In my scene class (inside my init method):

player = SKSpriteNode(imageNamed: "playerImg")
    player.position = CGPointMake(gameBoard.size.width/2, -(gameBoard.size.height + 55))
    player.size = CGSize(width: 40,height: 40)
    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
    player.physicsBody?.dynamic = false
    player.physicsBody?.categoryBitMask = BodyType.bro.rawValue
    player.physicsBody?.contactTestBitMask = BodyType.bro.rawValue
    player.physicsBody?.affectedByGravity = true

In anther custom method I have (still in the same scene class):

let sprite = SKSpriteNode(texture: texture)

    sprite.position = pointForColumn(block.column, row: block.row - 2)
    block.sprite = sprite

    sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
    sprite.physicsBody?.dynamic = false
    sprite.physicsBody?.categoryBitMask = BodyType.bro.rawValue
    sprite.physicsBody?.contactTestBitMask = BodyType.bro.rawValue
    sprite.physicsBody?.affectedByGravity = true

Here is my BodyType enum:

enum BodyType:UInt32 {

    case bro = 1
    case ground = 2
    case anotherBody1 = 4
    case anotherBody2 = 8
    case anotherBody3 = 16

}

And finally, inside my didMoveToView method I have:

physicsWorld.contactDelegate = self
    view.showsPhysics = true

So, I see the green border around my objects, but when they touch I have nothing inside the didBeginContact method (here attached a screenshot). Anyone, some idea about what is missing in order to have a trigger when collision detected ?

在此处输入图片说明

I got it. I had to put

        sprite.physicsBody?.dynamic = true
        sprite.physicsBody?.affectedByGravity = false

and after that it works like a charm.

You're setting the contactTestBitMask , not the collisionBitMask . The former just makes SpriteKit notify you of contacts between bodies, but doesn't change anything in the physics simulation on contact. You need the latter for a contact to turn into a collision (and for the collision to be resolved, making the bodies stop or bounce off one another).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM