无法更改SKSpriteNode的纹理

时间:2018-03-06 17:55:30

标签: swift sprite-kit skspritenode sktexture

在我的游戏中,我正在创建一个具有特定纹理的Circle对象,但是例如,如果Circle击中某个墙,我希望其纹理发生变化。不幸的是,由于某种原因这不起作用,我不知道为什么。 这是我的Circle类的代码:

class Circle: SKNode, GKAgentDelegate{
    let txtName = "farblos"

    var node: SKSpriteNode {
        let node = SKSpriteNode(imageNamed: txtName)
        node.size = CGSize(width: 30, height: 30)
        node.name = "circle"

        return node
    }

    let agent: GKAgent2D

    init(position: CGPoint) {
        agent = GKAgent2D()
        agent.position = vector_float2(x: Float(position.x), y: Float(position.y))
        agent.radius = Float(15)
        agent.maxSpeed = 50.0
        agent.maxAcceleration = 20.0
        super.init()

        self.position = position
        agent.delegate = self
        addChild(node)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

出于测试目的,我在将节点添加为子节点后直接添加了这段代码。

node.texture = SKTexture(imageNamed: "cyan")

加载纹理时没有错误。图像肯定存在,我可以从中创建一个SKTexture。

你知道为什么纹理不会改变吗?

这就是Circle对象的创建方式:

for _ in 1...i {
    let entity = Circle(position: CGPoint.randomPoint(inBounds: b, notCollidingWith: allBoundaries))

    agentSystem.addComponent(entity.agent)
    allCircles.append(entity)

    self.addChild(entity)
}

此代码正在场景中的didMoveTo方法中执行。

在碰撞时,这是我的代码:

override func didBegin(_ contact: SKPhysicsContact, with circle: Circle) {
    circle.physicsBody?.collisionBitMask = CollisionCategoryBitmask.allExcept(c).rawValue
    circle.node.texture = txt
}

txt在这里创建:

var txt: SKTexture{
        get{
            return SKTexture(imageNamed: c)
        }
    }

c是一个值为“cyan”的字符串

2 个答案:

答案 0 :(得分:2)

问题在于这一点......

var node: SKSpriteNode {
    let node = SKSpriteNode(imageNamed: txtName)
    node.size = CGSize(width: 30, height: 30)
    node.name = "circle"

    return node
}

每次访问节点时,都会重新分配纹理“txtName”

它需要......

lazy var node: SKSpriteNode = {
    let node = SKSpriteNode(imageNamed: txtName)
    node.size = CGSize(width: 30, height: 30)
    node.name = "circle"

    return node
}()

答案 1 :(得分:0)

在我看来,这不起作用的原因是因为"节点"的计算值。变量

当您引用"节点"时,您正在做的是创建一个新节点。变量。当你addChild(node)时 你正在做两件事:创建一个新节点,然后将其添加为场景的子节点。

所以,如果你这样做的话 node.texture = SKTexture(imageNamed: "cyan") 您正在创建一个新节点并设置其纹理,但这与您添加到场景中的节点不同。

要避免这种情况,请将创建的节点保存在变量中,并使用该变量设置新纹理。

它对我有用:)希望这有帮助