Jarron
Jarron

Reputation: 1049

Increase Sprite ContainsPoint Size

I have a sprite which has had it size reduced to 0.8. When I use sprite.ContainsPoint(touchLocation), the touches are only registered within 0.8 of the original size sprite (which make sense). However, even though the sprite has been reduced, I still want the touches to register as if the sprite was still at full size (1.0). Below is my current code:

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

    }

}

What I have tried which doesn't work, but you might be able to see what I'm trying to do:

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

    }

}

Any help would be great!

Upvotes: 0

Views: 127

Answers (1)

Ivens Denner
Ivens Denner

Reputation: 533

You could add another SKSpriteNode as a child of the button, to be the actual sprite of the button, while the button itself would had no texture or color. This way, you could reduce just the child sprite node, and make the hit test within the button itself.

For example:

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

Upvotes: 2

Related Questions