gpt4 book ai didi

swift - 将节点定位在屏幕底部下方(Spritekit)

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:35 25 4
gpt4 key购买 nike

您好,我正在尝试在屏幕底部生成子弹向上移动,但我当前的代码是在屏幕顶部生成子弹。我试过使高度为负,但什么也没发生。这是我正在使用的代码,谢谢。

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)) 从场景中完全隐藏你的节点。

现在记住,如果你的节点在不同的父节点之间移动,这个惰性将不会更新。

另请注意,我用 ! 展开了所有选项,您可能想使用 ?并首先检查它是否存在。

关于swift - 将节点定位在屏幕底部下方(Spritekit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575988/

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