Swift比较两个颜色对象,看它们的颜色是否与触摸相同

时间:2015-07-23 15:07:34

标签: swift sprite-kit

choiceBall设置为黑色,但随机改变颜色以匹配每个点击的其他球。我的想法是根据choiceBall的颜色点击其他球。

例如:choiceBall变为蓝色。我碰到了蓝色的球。 choiceBall变红了我触摸红球等。

如何根据choiceBall检查我是否点击了正确的球。这样我就可以实施一个记分板来保持分数。

感谢您的帮助:)

class GameScene: SKScene {

   var choiceBall = SKShapeNode(circleOfRadius: 50)
   var blueBall = SKShapeNode(circleOfRadius: 50)
   var greenBall = SKShapeNode(circleOfRadius: 50)
   var yellowBall = SKShapeNode(circleOfRadius: 50)
   var redBall = SKShapeNode(circleOfRadius: 50)

   var array = [SKColor(red: 0.62, green: 0.07, blue: 0.04, alpha: 1), SKColor(red: 0, green: 0.6, blue: 0.8, alpha: 1), SKColor(red: 0, green: 0.69, blue: 0.1, alpha: 1), SKColor(red: 0.93, green: 0.93, blue: 0, alpha: 1)]

 override func didMoveToView(view: SKView) {

    choiceBall.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
    choiceBall.fillColor = SKColor.blackColor()
    self.addChild(choiceBall)

    blueBall.position = CGPointMake(self.frame.size.width * 0.35, self.frame.size.height * 0.25)
    blueBall.fillColor = SKColor(red: 0, green: 0.6, blue: 0.8, alpha: 1)
    self.addChild(blueBall)

    redBall.position = CGPointMake(self.frame.size.width * 0.65, self.frame.size.height * 0.75)
    redBall.fillColor = SKColor(red: 0.62, green: 0.07, blue: 0.04, alpha: 1)
    self.addChild(redBall)

    yellowBall.position = CGPointMake(self.frame.size.width * 0.35, self.frame.size.height * 0.75)
    yellowBall.fillColor = SKColor(red: 0.93, green: 0.93, blue: 0, alpha: 1)
    self.addChild(yellowBall)

    greenBall.position = CGPointMake(self.frame.size.width * 0.65, self.frame.size.height * 0.25)
    greenBall.fillColor = SKColor(red: 0, green: 0.69, blue: 0.1, alpha: 1)
    self.addChild(greenBall)
}

 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    choiceBall.fillColor = array[randomIndex]
}

1 个答案:

答案 0 :(得分:2)

基本上你需要检查与所有球碰撞的所有触摸,如果它们碰撞,你可以检查颜色。如果您不想检查水龙头,请不要忘记跳过选择球。

for t in touches { // check each touch
    let touch = t as! UITouch // convert to UITouch for pre Swift 2.0
    let pos = touch.locationInNode(self) // find touch position

    for child in self.children { // check each children in scene
        if let ball = child as? SKShapeNode { // convert child to the shape node
            if ball !== choiceBall && ball.containsPoint(pos) { // check for collision, but skip if it's a choice ball
                if ball.fillColor == choiceBall.fillColor { // collision found, check color
                    // do your stuff, colors match
                }
            }
        }
    }
}
相关问题