How to know which SKSpriteNode is affected by collision detection in Swift?

余生长醉 提交于 2019-12-30 06:49:54

问题


Situation: I have two or more ships on my iOS screen. Both have different attributes like name, size, hitpoints and score points. They are displayed as SKSpriteNodes and each one has added a physicsBody.

At the moment those extra attributes are variables of an extended SKSpriteNode class.

import SpriteKit    
class ship: SKSpriteNode {
            var hitpoints: Int = nil?
            var score: Int = nil?

        func createPhysicsBody(){
            self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
            self.physicsBody?.dynamic = true
            ...
        }
    }

In this 'game' you can shoot at those ships and as soon as a bullet hits a ship, you get points. 'Hits a ship' is detected by collision.

func didBeginContact(contact: SKPhysicsContact){    
    switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
        case shipCategory + bulletCategory:
            contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
            break;
        default:
            break;
    }
}

Problem: Collision detection just returns a physicsBody and I do not know how to get my extended SKSpriteNode class just by this physicsBody.

Thoughts: Is it a correct way to extend SKSpriteNode to get my objects like a ship to life? When I add a ship to my screen it looks like:

var ship = Ship(ship(hitpoints: 1, score: 100), position: <CGPosition>)
self.addChild(ship)

Or is this just a wrong approach and there is a much better way to find out which object with stats so and so is hit by a bullet thru collision detection?

This question is similar to my other question - I just want ask this in broader sense.


回答1:


The SKPhysicsBody has a property node which is the SKNode associated to the body. You just need to perform a conditional cast to your Ship class.

    if let ship = contact.bodyA.node as? Ship {
        // here you have your ship object of type Ship
        print("Score of this ship is: \(ship.score)!!!")
    }

Please note that the Ship node could be the one associated with bodyB so.

    if let ship = contact.bodyA.node as? Ship {
        // here you have your ship...
    } else if let ship = contact.bodyB.node as? Ship {
        // here you have your ship...
    }

Hope this helps.



来源:https://stackoverflow.com/questions/31812108/how-to-know-which-skspritenode-is-affected-by-collision-detection-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!