无法更改SKSpriteNode的纹理

问题描述 投票:2回答:2

在我的游戏中,我正在创建一个具有特定纹理的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是一个值为“青色”的字符串

swift sprite-kit skspritenode sktexture
2个回答
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
}()

0
投票

在我看来,这不起作用的原因是因为“node”变量的计算值。

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

因此,如果您执行node.texture = SKTexture(imageNamed: "cyan"),您将创建一个新节点并设置其纹理,但这与您添加到场景中的节点不同。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.