简体   繁体   中英

iOS Collision Detection

I have tried and tried to get collision detection to work the way I need but to no avail. What I want to accomplish is to get notified when the character touches an object but not stop it from moving on to the object. In GameScene , I have the physics of the object set like this:

Category Mask: 8
Collision Mask: 0
Field Mask: 0
Contact Mask: 0

I add the character to the scene in my code. I have a category structure like this:

struct PhysicsCategory {
    static let None: UInt32 = 0
    static let Player: UInt32 = 0b1 // 1
    static let Pillar:UInt32 = 0b10// 2
    static let Chest:UInt32 = 0b100// 4
    static let Ladder:UInt32 = 0b1000
}

And the character physics is like this:

 playerWalk.physicsBody?.categoryBitMask=PhysicsCategory.Player
 playerWalk.physicsBody?.collisionBitMask=PhysicsCategory.Pillar
 playerWalk.physicsBody?.contactTestBitMask=PhysicsCategory.Chest | PhysicsCategory.Ladder

 playerWalk.physicsBody = SKPhysicsBody(rectangleOf:
        playerWalk.frame.size)

For some reason the character stops at the ladder instead of moving on top of it. I can't figure out what I'm doing wrong.

Edit - You've set the properties of the playerWalk physics body before you've actually created the playerWalk.physicsBody . So the values for the categoryBitMask , collisionBitMask and contactTestBitMask don't get set because you've used optional chaining and so playerWalk.physicsBody? resolved to nil and nothing gets set.

Then, when you create the playerWalk physic body it just has the defaults properties ie no category, no contacts and collides with everything, so it is colliding with your ladder and thus cannot move over it.

Move the line:

playerWalk.physicsBody = SKPhysicsBody(rectangleOf: playerWalk.frame.size)

to before the lines where you set the physics body's properties.

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