gpt4 book ai didi

swift - SKAction runAction 不执行完成 block

转载 作者:IT王子 更新时间:2023-10-29 05:49:22 25 4
gpt4 key购买 nike

SKSpriteNodeSKNode 的子节点,并放置在 SKSpriteNode 数组中用于存储目的。

SKSpriteNode 使用动画删除。在此动画结束时,执行完成 block 以执行一些语句...

删除必须同时发生在 SKSpriteNode 父节点和数组中。根据这 2 个删除的顺序,结果是否正确:

  • 如果从 1/数组中删除 SKSpriteNode,然后从 SKNode 父数组中删除 2/,则执行完成 block 。
  • 如果顺序相反,1/SKNode parent's then 2/the array, completion block is not executed.

为什么会这样?

for position in listOfPositions {

theSprite:SKSpriteNode = theGrid[position]

/// the SKSpriteNode referenced by theSprite :
/// - belongs to an array of SKSpriteNode: theGrid
/// - belongs to a SKNode: theGameLayer
///
/// In other words this SKSpriteNode is referenced twice
///

let theActions = SKAction.sequence([
/// Some actions here
/// ...

/// Remove theSprite from the Grid
/// - position is an instance of a structure of my own
/// - theGrid is accessed via a subscript
///
SKAction.runBlock({self.theGrid[position] = nil}),

/// remove theSprite from it's parent
SKAction.removeFromParent(),
])

theSprite.runAction(theActions,completion:{NSLog("Deleted")})
}

显示完成消息。

现在如果 removeFromParent 被放置在从 theGrid 中删除操作之前,如下所示,完成不会执行:

let theActions = SKAction.sequence([
/// Some actions here
/// ...

/// remove theSprite from it's parent
SKAction.removeFromParent(),

/// remove theSprite from the Grid
SKAction.runBlock({self.theGrid[position] = nil}),
])

最佳答案

来自SKAction Reference :

An SKAction object is an action that is executed by a node in the scene (SKScene)...When the scene processes its nodes, actions associated with those nodes are evaluated.

换句话说,当且仅当该节点在场景中时,该节点的 Action 才会运行。通过调用 removeFromParent,您可以从场景中移除节点,永远不会调用 runBlock 操作(因为节点不再存在于场景中),因此序列永远不会完成的。由于序列未完成,因此不会调用完成 block 。

为了安全起见,我建议将 removeFromParent 调用移至完成 block 。这样的事情感觉更安全:

for position in listOfPositions {

let theSprite: SKSpriteNode = theGrid[position]

/// the SKSpriteNode referenced by theSprite :
/// - belongs to an array of SKSpriteNode: theGrid
/// - belongs to a SKNode: theGameLayer
///
/// In other words this SKSpriteNode is referenced twice
///

let theActions = SKAction.sequence([
/// Some actions here
/// ...

/// Remove theSprite from the Grid
/// - position is an instance of a structure of my own
/// - theGrid is accessed via a subscript
///
SKAction.runBlock({self.theGrid[position] = nil})
])

theSprite.runAction(theActions) {
/// remove theSprite from it's parent
/// Might need to weakly reference self here
theSprite.removeFromParent(),
NSLog("Deleted")
}
}

长话短说
序列未完成,因此不会调用序列的完成 block 。

关于swift - SKAction runAction 不执行完成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30599078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com