我有一个精灵,它的大小减少到0.8。当我使用sprite.ContainsPoint(touchLocation)时,触摸仅在原始大小精灵的0.8内注册(这是有意义的)。然而,即使精灵已经减少了,我仍然希望触摸注册,好像精灵仍然是全尺寸(1.0)。以下是我目前的代码:
var button: SKSpriteNode!
func createButton() {
button = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(100, 100))
addChild(button)
button.runAction(SKAction.scaleTo(0.8, duration: 1))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch!
let touchLocation = touch.locationInNode(self)
if button.containsPoint(touchLocation) {
print("touching within the button")
}
}
我尝试过哪些不起作用,但您可能会看到我正在尝试做的事情:
var button: SKSpriteNode!
func createButton() {
button = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(100, 100))
addChild(button)
button.runAction(SKAction.scaleTo(0.8, duration: 1))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch!
let touchLocation = touch.locationInNode(self)
let myButton = CGRectMake(button.position.x, button.position.y, button.size.width / 0.8, button.size.width / 0.8)
//// the button.size / 0.8 should bring the size back to 1.0
if myButton.containsPoint(touchLocation) {
print("touching within the button")
}
}
任何帮助都会很棒!
答案 0 :(得分:2)
你可以添加另一个SKSpriteNode
作为按钮的子项,作为按钮的实际精灵,而按钮本身没有纹理或颜色。这样,您可以只减少子精灵节点,并在按钮本身内进行命中测试。
例如:
var button: SKSpriteNode!
func createButton() {
button = SKSpriteNode(color: UIColor.clearColor(), size: CGSizeMake(100, 100))
addChild(button)
buttonSprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(100, 100))
button.addChild(buttonSprite)
buttonSprite.runAction(SKAction.scaleTo(0.8, duration: 1))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch!
let touchLocation = touch.locationInNode(self)
if button.containsPoint(touchLocation) {
print("touching within the button")
}
}