gpt4 book ai didi

ios - 自定义 SKSpriteNode addChild 不工作

转载 作者:可可西里 更新时间:2023-11-01 02:18:40 26 4
gpt4 key购买 nike

我正在尝试使用 SpriteKit 和 Swift 开发一款需要在所有场景中具有共同背景的游戏。由于背景是普通的并且它的 Action 需要连续,我创建了一个 SKSpriteNode 的自定义单例子类,如下所示:

class BackgroundNode: SKSpriteNode {
static let sharedBackground = BackgroundNode()

private init()
{
let texture = SKTexture(imageNamed: "Background")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
addActors()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

private func addActors() {
addClouds()
}

private func addClouds() {
addCloud1()
}

private func addCloud1() {
let cloud1 = SKSpriteNode(imageNamed: "Cloud1")
cloud1.size = CGSizeMake(0.41953125*self.size.width, 0.225*self.size.height)
cloud1.position = CGPointMake(-self.size.width/2, 0.7*self.size.height)
self.addChild(cloud1)
let moveAction = SKAction.moveTo(CGPointMake(self.size.width/2, 0.7*self.size.height), duration: 20)
cloud1.runAction(SKAction.repeatActionForever(moveAction))
}
}

然后从 GameScene 类中,我将此节点添加到当前 View ,如下所示:

class GameScene: SKScene {
override func didMoveToView(view: SKView) {
BackgroundNode.sharedBackground.size = CGSizeMake(self.size.width, self.size.height)
BackgroundNode.sharedBackground.position = CGPointMake(self.size.width/2, self.size.height/2)
addChild(BackgroundNode.sharedBackground)
}
}

背景图像显示正确,但未添加云。从上面的代码开始云应该出现在屏幕外并通过另一边动画进入屏幕然后再次离开屏幕,但为了验证它是否被添加,我什至尝试将云添加到屏幕中央而不用任何动画。云还是没有出现。这可能是什么问题?以及如何解决?

编辑

我发现 child 实际上正在添加,但正在添加并移动到屏幕上方的一些点。我还发现它可能与云的 anchor 有关,但无论我将哪个值设置为 anchor ,云始终保持在屏幕的右上角。我可以对 anchor 做些什么来使云看起来像它应该的那样(将左下角视为 (0, 0) 是我想要的)

最佳答案

解决了这个问题。问题是我必须手动设置场景和节点的 anchor 。将场景和节点的 anchor 设置为 (0, 0) 解决了这个问题。新代码如下所示:

游戏场景

override func didMoveToView(view: SKView) {
anchorPoint = CGPointMake(0, 0) //Added this
BackgroundNode.sharedBackground.size = CGSizeMake(self.size.width, self.size.height)
BackgroundNode.sharedBackground.position = CGPointMake(0, 0)
addChild(BackgroundNode.sharedBackground)
}

背景节点

private init()
{
let texture = SKTexture(imageNamed: "Background")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
anchorPoint = CGPointMake(0, 0) //Added this
addActors()
}

关于ios - 自定义 SKSpriteNode addChild 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593622/

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