碰撞检查问题

时间:2015-07-24 15:09:35

标签: swift if-statement sprite-kit

代码检查用户是否使用与随机更改纹理的球相同的纹理来点击球。但是在我的控制台" Point"只是偶尔打印,虽然我点击的球具有与随机改变纹理的球相同的纹理。如何解决这个问题。这与将physicsBody添加到其他球有关吗?

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")
                    }
                }
            }
        }
    }


}

2 个答案:

答案 0 :(得分:1)

一些观察......

  1. nodeAtPoint(pos)可以替换子节点上的for循环
  2. ball.containsPoint(pos)不需要,因为nodeAtPoint执行相同的测试
  3. ball !== blackB应为ball != blackB
  4. 在检查纹理匹配后,或许更改为随机纹理更有意义
  5. 具有上述更改的实施

    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]
    }
    

答案 1 :(得分:0)

我认为你希望当你触摸同一个纹理球时必须发生一些事情......

&#13;
&#13;
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
}
&#13;
&#13;
&#13;

更新

&#13;
&#13;
if(ball.texture == blackB.texture){
  println("POINT");
  score+=1;
  label.text = String(score); // Update the label.text value everytime score changes
}
&#13;
&#13;
&#13;