gpt4 book ai didi

ios - Spritekit 相机节点缩放但固定场景底部

转载 作者:行者123 更新时间:2023-11-29 05:27:22 25 4
gpt4 key购买 nike

我有一个缩放为 1 的相机节点。当我运行游戏时,我希望它缩小(即缩小),但将“地板”保留在底部。我将如何将相机节点固定到场景的底部并有效地“向上”缩放(很难解释)。因此场景的底部保持在底部,但其余部分缩小。

我尝试过 SKConstraints,但没有任何运气(我对 SpriteKit 还很陌生)

func setConstraints(with scene: SKScene, and frame: CGRect, to node: SKNode?) {
let scaledSize = CGSize(width: scene.size.width * xScale, height: scene.size.height * yScale)
let boardContentRect = frame

let xInset = min((scaledSize.width / 2), boardContentRect.width / 2)
let yInset = min((scaledSize.height / 2), boardContentRect.height / 2)
let insetContentRect = boardContentRect.insetBy(dx: xInset, dy: yInset)

let xRange = SKRange(lowerLimit: insetContentRect.minX, upperLimit: insetContentRect.maxX)
let yRange = SKRange(lowerLimit: insetContentRect.minY, upperLimit: insetContentRect.maxY)

let levelEdgeConstraint = SKConstraint.positionX(xRange, y: yRange)

if let node = node {
let zeroRange = SKRange(constantValue: 0.0)
let positionConstraint = SKConstraint.distance(zeroRange, to: node)
constraints = [positionConstraint, levelEdgeConstraint]
} else {
constraints = [levelEdgeConstraint]
}


}

然后调用该函数:

gameCamera.setConstraints(with: self, and: scene!.frame, to: nil)

(这是我正在关注的教程中的代码)“setConstraints”函数是 SKCameraNode 的扩展

我不确定这会给我正确的输出,但是当我运行代码进行缩放时,它只是从中间缩放并显示场景 .sks 文件的周围区域。

gameCamera.run(SKAction.scale(to: 0.2, duration: 100))

这是缩放游戏相机的代码

编辑:下面的答案几乎就是我正在寻找的,这是我更新的答案:

let scaleTo = 0.2
let duration = 100
let scaleTop = SKAction.customAction(withDuration:duration){
(node, elapsedTime) in
let newScale = 1 - ((elapsedTime/duration) * (1-scaleTo))
let currentScaleY = node.yScale
let currentHeight = node.scene!.size.height * currentScaleY
let newHeight = node.scene!.size.height * newScale
let heightDiff = newHeight - currentHeight
let yOffset = heightDiff / 2
node.setScale(newScale)
node.position.y += yOffset
}

最佳答案

您无法使用约束,因为您的比例大小是动态的。

相反,您需要移动相机位置以产生仅在 3 个方向上缩放的错觉。

为此,我建议创建一个自定义操作。

let scaleTo = 2.0
let duration = 1.0
let currentNodeScale = 0.0
let scaleTop = SKCustomAction(withDuration:duration){
(node, elapsedTime) in
if elapsedTime == 0 {currentNodeScale = node.scale}
let newScale = currentNodeScale - ((elapsedTime/duration) * (currentNodeScale-scaleTo))
let currentYScale = node.yScale
let currentHeight = node.scene.size.height * currentYScale
let newHeight = node.scene.size.height * newScale
let heightDiff = newHeight - currentHeight
let yOffset = heightDiff / 2
node.scale(to:newScale)
node.position.y += yOffset

}

它的作用是将相机的新高度与旧高度进行比较,并将其移动 1/2 的距离。

因此,如果您当前的高度为 1,这意味着您的相机在 y 轴上看到的是 [-1/2 到 1/2]。如果新的缩放高度为 2,那么您的相机会在 y 轴上看到 [-1 到 1]。我们需要向上移动相机,以便相机看到 [-1/2 到 3/2],这意味着我们需要添加 1/2。所以我们做 2 - 1,即 1,然后走该距离的 1/2。这使得我们的 yOffset 为 1/2,您可以将其添加到相机中。

关于ios - Spritekit 相机节点缩放但固定场景底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58032234/

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