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

Situation: I have two or more ships on the iOS screen. Both have different attributes such as name, size, hitpoints and points. They appear as SKSpriteNodes , and each of them added physicsBody .

These additional attributes are currently variables of the SKSpriteNode extended 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 on these ships, and as soon as the bullet hits the ship, you get points. β€œShip Impact” detected in a 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: Conflict detection simply returns a physical element, and I don't know how to get this extended SKSpriteNode class SKSpriteNode just this physical block.

Thoughts: Is this the right way to extend SKSpriteNode to animate my objects like a ship? When I add a ship to my screen, it looks like this:

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

Or is this just the wrong approach, and is there a much better way to find out which object with statistics is already hit by a bullet through collision detection?

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

+5
source share
1 answer

SKPhysicsBody has a node property, which is the SKNode associated with the body. You just need to do a conditional cast for 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)!!!") } 

Note that Ship node may be one related to bodyB like this.

  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.

+8
source

All Articles