Oren Edrich Oren Edrich - 1 year ago 109
Swift Question

Working with SKSpritenodes and textures

I am trying to program in feature that allows the user to change the "Ghost" to a different image.

Here is my code:

Ghost = SKSpriteNode(imageNamed: "Ghost17")
Ghost.size = CGSize(width: 50, height: 50)
Ghost.position = CGPoint(x: self.frame.width / 2 - Ghost.frame.width, y: self.frame.height / 2)
Ghost.physicsBody = SKPhysicsBody(circleOfRadius: Ghost.frame.height / 1.4)
Ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost
Ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall
Ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall | PhysicsCatagory.Score
Ghost.physicsBody?.affectedByGravity = false
Ghost.physicsBody?.isDynamic = true
Ghost.zPosition = 2

if defaults1.integer(forKey: "Sphere") == 2 {
Ghost = SKSpriteNode(imageNamed: "Ghost13")
if defaults1.integer(forKey: "Sphere") == nil! {
Ghost = SKSpriteNode(imageNamed: "Ghost2")


I am using UserDefaults to send the information between the viewContollers.

When i click on the button that sets the defaults1 to 2 the new image pops up but it doesn't behave like it should. Im not sure how to fix this, if you need anymore info please ask.

Nik Nik
Answer Source

When changing the texture, try using this:

Ghost.texture = SKTexture(imageNamed: "Ghost13")

Rather than:

Ghost = SKSpriteNode(imageNamed: "Ghost13")

This only changes the texture property of the node rather than reinitializing it. You may be encountering the issues because you're resetting the node when you reinitialize it.

Hope this helps!