SpriteNode position versus touch location

230 Views Asked by At

So i'm using a spritenode with an image and I don't set the position of it. Funny enough I was having issues setting the position of it so I didn't and it by default was set to center of page (for obvious reason) which ended up being perfect. So now in my touchesbegan method i'm looking to change the said image IF the original image was pressed so i'm checking if the touched location is equal to the node (of the image)'s position. Then if that is true, I replace it with the new image which is called "nowaves".

    for touch in touches
    {
        let location = touch.location(in: self)
        if (location == audioPlaying.position)
        {
            audioPlaying = SKSpriteNode(imageNamed: "nowaves")
        }

        else
        {

Do you guys think I need to readd it? Well right as I asked that I tested it to no result. This is what I tried:

    audioPlaying.size = CGSize(width: frame.size.width / 13, height: frame.size.height / 20)
    addChild(audioPlaying)

If anyone has any idea what the problem is I would love some feedback, thank you :D

2

There are 2 best solutions below

0
On BEST ANSWER

To add on to @sweeper , I had all my initial image content in the scenedidLoad method, rather than that I created a new method that I was already using for another functionality to start the game and had the initial image there instead and now everything works well.

8
On

By default, the position property returns the coordinates of the center of the node. In other words, unless you touched the exact center of the sprite, if (location == audioPlaying.position) will never be true. However, you should be aware that touching a node's exact center point is practically impossible.

So we use another method. We just need to check if the touched node is the node you want.

let touchedNode = self.nodes(at: touch.location(in: self)).first
if touchedNode == audioPlaying {
    // I think setting the texture is more suitable here, instead of creating a new node.
    audioPlaying.texture = SKTexture(imageNamed: "nowaves")
}