问题
The code checks if the user taps a ball with the same texture as a ball that randomly changes textures. But in my console "Point" is only printed occasionally although I tap on the ball with the same texture as the ball that randomly changes texture. How can this be fixed. Has this something to do with adding a physicsBody to the other balls?
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var array = [blueTexture, redTexture, greenTexture, yellowTexture]// var with value of textures
var blackB = childNodeWithName("changeBall") as! SKSpriteNode
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
blackB.texture = array[randomIndex] // blackB is given a random texture
for t in touches { // check each touch
let touch = t as! UITouch
let pos = touch.locationInNode(self) // find touch position
for child in self.children { // check each children in scene
if let ball = child as? SKSpriteNode{
if ball !== blackB && ball.containsPoint(pos) { // check for collision, but skip if it's a blackB
if ball.texture == blackB.texture { // collision found, check color
println("POINT")
}
}
}
}
}
}
回答1:
Some observations...
nodeAtPoint(pos)
can replace thefor
loop over child nodesball.containsPoint(pos)
is not needed becausenodeAtPoint
performs the same testball !== blackB
should beball != blackB
- Perhaps changing to a random texture after checking for a texture match makes more sense
An implementation with the above changes
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var array = [blueTexture, redTexture, greenTexture, yellowTexture]
var blackB = childNodeWithName("changeBall") as! SKSpriteNode
if let touch = touches.first as? UITouch {
let pos = touch.locationInNode(self)
if let ball = nodeAtPoint(pos) as? SKSpriteNode {
if ball != blackB && ball.texture == blackB.texture {
println("POINT")
}
}
}
// Change texture after checking for a texture match
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
blackB.texture = array[randomIndex]
}
回答2:
I assume you wish that something must happen when you touch the same textured ball...
if ball.texture == blackB.texture {
println("POINT"); //This is the only instruction read by the computer and nothing else
}
if ball.texture == blackB.texture {
println("POINT");
doSomething();//Insert expected function like here
}
UPDATE
if(ball.texture == blackB.texture){
println("POINT");
score+=1;
label.text = String(score); // Update the label.text value everytime score changes
}
来源:https://stackoverflow.com/questions/31614021/collision-checking-issues