Sprite-Kit开始触摸错误



我试图创建一个方法,当我触摸一个名为StartSprite的精灵时,通过我的touchesbegan函数,它将在我的控制台中打印一些东西。但由于某些原因,当我点击精灵时,什么也没发生。这是我的代码。

import SpriteKit
class GameScene: SKScene {
let StartSprite = SKSpriteNode(imageNamed: "startLabel")

override func didMoveToView(view: SKView) {
    let borderRect = CGRect(x: 0 , y: 0 , width: 400, height: 725)

    let welcomeLabel = SKLabelNode(fontNamed: "welcome");
    welcomeLabel.text = "Welcome";
    welcomeLabel.fontColor = UIColor.whiteColor()
    welcomeLabel.fontSize = 65
    welcomeLabel.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 150)
    self.addChild(welcomeLabel)
   //StartLabel

    let rectangleBorder = SKShapeNode(rect: borderRect)
    rectangleBorder.position = CGPoint(x: 315, y: 25)
    rectangleBorder.strokeColor = UIColor.whiteColor()
    self.addChild(rectangleBorder)
    self.backgroundColor = UIColor.grayColor()

    StartSprite.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    self.addChild(StartSprite)

    println("Hello")
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let touchLocation = touch.locationInNode(self)
        if touchLocation == StartSprite.position{
            println("Touches")
        }
    }
}

您的代码要求您恰好触摸StartSprite.position的一个像素。

试试这个:

let p = StartSprite.convertPoint(touchLocation, fromNode: self)
if StartSprite.containsPoint(p) {
    print("touched StartSprite")
}

如果你想添加更多的按钮,你可能想这样做:

let target = nodeAtPoint(touchLocation)
if target == StartSprite {
    print("touched StartSprite"
}
// check other buttons here

最新更新