Search code examples
xcodeswiftskphysicsbody

physicsbody from image texture not working


i have the following line of code you can see below:

Enemy.physicsBody = SKPhysicsBody(texture: player.texture, size: player.size)

when i try to run this code i get the following error:

Value of optional type 'SKTexture ?' not unwrapped; did you mean to use '!' or '?'

can someone tell me what i am doing wrong!


Solution

  • The init method SKPhysicsBody(texture: player.texture, size: player.size) takes a SKTexture instance as opposed to an Optional<SKTexture> (aka. SKTexture?) instance which you provided. So the player.texture needs to be unwrapped.

    Assuming you know you've loaded your texture correctly and it is not nil:

    Enemy.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)
    

    Or to safely unwrap the texture:

    if let texture = player.texture {
      Enemy.physicsBody = SKPhysicsBody(texture: texture, size: player.size)
    }