Search code examples
swiftsprite-kitspriteskspritenodeskphysicsbody

Swift SpriteKit - Prevent sprite node from angular rotation


I am trying to prevent my sprite from rotating. I have had a look at some other StackOverflow answers but nothing helped me. When I move my sprite into another node or against the side of the physics boundary it rotates it.

This is what I have tried when initialising the sprite:

        let texture = SKTexture(imageNamed:character.image)
        let size = CGSize(width: character.width, height: character.height)
        player = playerNode
        player.name = "player"
        player.physicsBody?.isDynamic = true
        player.physicsBody?.allowsRotation = false
        player.physicsBody?.angularVelocity = 1
        player.texture = texture
        player.position = CGPoint(x:0, y:0)
        player.size = size

        // Physics
        player.physicsBody?.categoryBitMask = BodyType.player.rawValue
        player.physicsBody?.contactTestBitMask = BodyType.dot.rawValue
        player.physicsBody?.collisionBitMask = 0
        player.physicsBody = SKPhysicsBody(texture: texture, size: size)
        player.physicsBody?.linearDamping = 1
        player.physicsBody?.angularDamping = 1

Solution

  • Your player doesn't actually have a physics body until you get to this line inthe 'physics' section:

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

    so all of these lines to set properties on the physics body aren't doing anything:

        player.physicsBody?.isDynamic = true
        player.physicsBody?.allowsRotation = false
        player.physicsBody?.angularVelocity = 1
    
        // Physics
        player.physicsBody?.categoryBitMask = BodyType.player.rawValue
        player.physicsBody?.contactTestBitMask = BodyType.dot.rawValue
        player.physicsBody?.collisionBitMask = 0
    

    Move the creation of the physics body to the top of the 'physics' section, and all the physics body's property assignment after that.