基本上我有这个代码只适用于“bubble1”。如果我想要另一个气泡“bubble2”
,我是否需要创建许多相同类型的功能? func addBubbles() {
let bubble1 = SKSpriteNode(imageNamed: "bubble_purple")
//the new one I want to create
let bubble2 = SKSpriteNode(imageNamed: "bubble_green")
bubble1.name = "bubble1"
bubble1.physicsBody = SKPhysicsBody(circleOfRadius: bubble1.size.width * 0.5, center: CGPointZero)
bubble2.name = "bubble2"
bubble2.physicsBody = SKPhysicsBody(circleOfRadius: bubble1.size.width * 0.5, center: CGPointZero)
physicsWorld.contactDelegate = self
physicsWorld.gravity = CGVectorMake(0, 0)
//Physics implementation of the bubbles
bubble1.physicsBody?.dynamic = true
bubble1.physicsBody?.usesPreciseCollisionDetection = true
bubble1.physicsBody?.categoryBitMask = PhysicsCategory.Bubble
bubble1.physicsBody?.contactTestBitMask = PhysicsCategory.Cones
bubble1.physicsBody?.collisionBitMask = 0
bubble1.physicsBody?.allowsRotation = false
答案 0 :(得分:1)
只需创建一个扩展SKSpriteNode
的气泡类class Bubble : SKSpriteNode
{
convenience init(imageNamed name:String)
{
let texture = SKTexture(imageNamed:named)
self.init(texture:texture,color:UIColor.clearColor(),size: texture!.size())
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width * 0.5, center: CGPointZero)
//Physics implementation of the bubbles
self.physicsBody?.dynamic = true
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.categoryBitMask = PhysicsCategory.Bubble
self.physicsBody?.contactTestBitMask = PhysicsCategory.Cones
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.allowsRotation = false
}
}
然后就这样打电话给你的泡泡:
var bubble1 = Bubble(imageNamed:"bubble_purple")
bubble1.name = "bubble1"
var bubble2 = Bubble(imageNamed:"bubble_green")
bubble2.name = "bubble2"
这样做会覆盖以前的便捷方法,并且不允许你轻松地将它扩展到更多的类,所以我建议创建一个新的方法来初始化你的精灵,以防你需要扩展它的功能这个init就像这样:
init(named:String)
{
let texture = SKTexture(imageNamed:named)
super.init(texture:texture,color:UIColor.clearColor(),size: texture!.size())
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width * 0.5, center: CGPointZero)
//Physics implementation of the bubbles
self.physicsBody?.dynamic = true
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.categoryBitMask = PhysicsCategory.Bubble
self.physicsBody?.contactTestBitMask = PhysicsCategory.Cones
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.allowsRotation = false
}
并像这样打电话给你的泡泡:
var bubble1 = Bubble(named:"bubble_purple")
bubble1.name = "bubble1"
var bubble2 = Bubble(named:"bubble_green")
bubble2.name = "bubble2"