Working with SKSpritenodes and textures

我们两清 提交于 2019-12-11 03:51:44

问题


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")
    }

    self.addChild(Ghost)

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.


回答1:


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!



来源:https://stackoverflow.com/questions/40143183/working-with-skspritenodes-and-textures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!