I have figured out how to get func didBeginContact(contact: SKPhysicsContact)
to only be called once. This allows physics bodies with a texture SKPhysicsBody(texture: size:)
to count collisions once even though in reality (because of the nature of the texture's physics body) this function will be called multiple times.
Step 1:
Create a name property for the SKSpriteNode (we will use ball for this example)
and set it equal to a unique name. We can do this by creating a int
var number = 0
ball.name = "ball (number)"
This allows for a unique name evertime that object is created.
Step 2:
Create a array to hold these , append the ball to the array, increment the number
var array: [String] = []
var number = 0
ball.name = "ball (number)"
array.append(ball.name!)
number ++
Step 3: Now in the func didBeginContact(contact: SKPhysicsContact)
find out if the name is in the array. If it is increment the score, remove the node, and remove the name from the array. If the name is not in the array don't do anything.
Removing the name from the array allows us now to only count the function call once.
func didBeginContact(contact: SKPhysicsContact) {
if ( contact.bodyA.categoryBitMask & BodyType.shield.rawValue ) == BodyType.shield.rawValue {
var name = contact.bodyB.node?.name!
let index = find(array, name!)
if contains(array, name!) {
score++
contact.bodyB.node?.removeFromParent()
array.removeAtIndex(index!)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…