Search code examples
iosswiftsprite-kitskphysicsbody

How can I check a sprites position on the x axis during update


I want to detect what direction the sprite is moving in without using a physics body.

I tried using a physics body as shown below:

 if player!.physicsBody!.velocity < 0 {
//Referencing operator function '<' on 'BinaryInteger' requires that 'CGVector' conform to 
'BinaryInteger' *****
            player! = SKSpriteNode(texture: leftFrameTexture)
        }

        else if player!.physicsBody!.velocity > 0 {
//Referencing operator function '<' on 'BinaryInteger' requires that 'CGVector' conform to 
    'BinaryInteger' *****
            player! = SKSpriteNode(texture: firstFrameTexture)
        }

but get the error: Referencing operator function '<' on 'BinaryInteger' requires that 'CGVector' conform to 'BinaryInteger'

There must be an easier way. I don't need any of the physics except for velocity and I wont need velocity if I can tell the direction of the sprite movement


Solution

  • Velocity is a vector and vectors have a direction but no natural ordering. If you're interested in just the x-axis and whether the player is moving left or right, you want the x-component of the velocity:

    if player!.physicsBody!.velocity.dx < 0 {
       // Stuff for when the player is moving left
       ...
    }
    

    Also, you probably don't want to change the player node like player! = SKSpriteNode(texture: leftFrameTexture) because you're throwing away everything associated with the player, like the physics body, the location, orientation, scale, etc. It looks like you just want to change the texture, so:

    if player!.physicsBody!.velocity.dx < 0 {
       player!.texture = leftFrameTexture
    } ...