[英]How to know which SKSpriteNode is affected by collision detection in Swift?
Situation: I have two or more ships on my iOS screen. 情况:我的iOS屏幕上有两艘或更多船。 Both have different attributes like name, size, hitpoints and score points. 两者都有不同的属性,如名称,大小,生命值和得分。 They are displayed as SKSpriteNodes
and each one has added a physicsBody
. 它们显示为SKSpriteNodes
,每个都添加了一个physicsBody
。
At the moment those extra attributes are variables of an extended SKSpriteNode
class. 目前,这些额外属性是扩展SKSpriteNode
类的变量。
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. 问题:碰撞检测只返回一个physicsBody,我不知道如何通过这个physicsBody得到我的扩展SKSpriteNode
类。
Thoughts: Is it a correct way to extend SKSpriteNode
to get my objects like a ship to life? 思考:扩展SKSpriteNode
以使我的对象像船只一样生命,这是一种正确的方法吗? 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. 这个问题与我的另一个问题类似 - 我只想在更广泛的意义上问这个问题 。
The SKPhysicsBody
has a property node
which is the SKNode
associated to the body. SKPhysicsBody
有一个属性node
,它是与SKNode
相关的SKNode
。 You just need to perform a conditional cast
to your Ship
class. 您只需要对Ship
类执行conditional cast
转换。
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. 请注意, Ship
节点可以是与bodyB
关联的节点。
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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.