您好,我正在尝试在屏幕底部生成项目符号以向上移动,但我拥有的当前代码会在屏幕顶部生成项目符号。我试过将高度设为负数,但没有任何反应。这是我正在使用的代码,谢谢。
let randomBulletPosition = GKRandomDistribution(lowestValue: -300, highestValue: 300)
let position = CGFloat(randomBulletPosition.nextInt())
bullet.position = CGPoint(x: position, y: self.frame.size.height + bullet.size.height)
一些不错的转换会帮助你。
现在,不要一直这样做,这应该是一个一次性完成类型的交易,就像在lazy
属性中一样。
首先,我们想深入了解我们的观点
let viewBottom = CGPoint(x:scene!.view!.midX,y:scene!.view!.frame.maxY) //In a UIView, 0,0 is the top left corner, so we look to bottom middle
二、我们要把位置转换为场景
let sceneBottom = scene!.view!.convert(viewBottom, to:scene!)
最后,我们希望转换为您需要它成为其中一部分的任何节点。 (如果要将其放置在场景中,这是可选的(
let nodeBottom = scene!.convert(sceneBottom,to:node)
代码应如下所示:
let viewBottom = CGPoint(x:scene!.view!.midX,y:scene!.view!.frame.maxY)
let sceneBottom = scene!.view!.convert(viewBottom!, to:scene!)
let nodeBottom = scene!.convert(sceneBottom,to:node)
当然,这有点丑。
值得庆幸的是,我们有convertPoint和convert(_from:(来清理一下东西
let sceneBottom = scene.convertPoint(from:viewBottom)
这意味着我们可以清理代码,使其如下所示:
let sceneBottom = scene.convertPoint(from:CGPoint(x:scene!.view!.midX,y:scene!.view!.frame.maxY))
let nodeBottom = node.convert(sceneBottom,from:scene!)
然后我们可以把它变成 1 行为:
let nodeBottom = node.convert(scene.convertPoint(from:CGPoint(x:scene!.view!.midX,y:scene!.view!.frame.maxY),from:scene!)
只要节点对类可用,我们就可以让它变得懒惰:
lazy var nodeBottom = self.node.convert(self.scene!.convertPoint(CGPoint(x:self.scene!.view!.midX,y:self.scene!.view!.frame.maxY),from:self.scene!)
这意味着当你第一次调用nodeBottom时,它将为你做这些计算并将其存储到内存中。 此后的每次,都会保留该数字。
现在您知道屏幕底部在要使用的坐标系中的位置,您可以将 x 值分配给随机产生的任何值,并且可以减去 (node.height * (1 - node.anchorPoint.y(( 以完全隐藏您的节点。
现在请记住,如果您的节点在不同的父节点之间移动,则此懒惰将不会更新。
另请注意,我用 ! 解开了所有选项,您可能想使用 ? 并首先检查它是否存在。