gpt4 book ai didi

sprite-kit - 将背景颜色淡化为另一种颜色的替代方法

转载 作者:行者123 更新时间:2023-12-03 09:32:36 24 4
gpt4 key购买 nike

在我的触摸开始方法中,我放置了这行简单的代码,它将背景颜色淡化为红色。

 runAction(SKAction.colorizeWithColor(SKColor.redColor(), colorBlendFactor: 1.0, duration: 1.0))

一切正常,但问题是代码在使用 ios 7 时没有做任何事情。我想知道是否有其他方法可以使背景淡入不同的颜色,或者是否有此代码的 ios 7 版本.

最佳答案

有多种方法可以从一种颜色过渡到另一种颜色。最直接的方法之一是在两种颜色之间进行线性插值,方法是将逐渐增大的起始颜色的 RGB 分量与逐渐减小的结束颜色的 RBG 分量相结合:

red = starting_red * (1.0 - fraction) + ending_red * fraction
green = starting_green * (1.0 - fraction) + ending_green* fraction
blue = starting_blue * (1.0 - fraction) + ending_blue * fraction

哪里 fraction从 0 开始到 1 结束,增量为
fraction += delta_time * step_size

实现此方法的一种方法是将代码添加到 didMoveToView GameScene的方法.但是,如果您的游戏包含多个场景,更好的策略是扩展 SKAction添加一个创建自定义 Action 的类方法,以便所有场景都可以使用它。

首先,定义一个结构来存储开始和结束的 RGB 颜色分量。将此添加到 GameScene 的定义之外.
struct ColorComponents {
var red:CGFloat
var green:CGFloat
var blue:CGFloat

init(color:SKColor) {
self.init()
var alpha:CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
}

init() {
red = 0
green = 0
blue = 0
}
}

然后,扩展 SKAction通过添加以下方法将背景颜色更改为另一种颜色。请注意,扩展必须在类之外定义。
extension SKAction {
static func changeColor(startColor:SKColor, endColor:SKColor, duration:NSTimeInterval) -> SKAction {
// Extract and store starting and ending colors' RGB components
let start = ColorComponents(color: startColor)
let end = ColorComponents(color: endColor)
// Compute the step size
let stepSize = CGFloat(1/duration)
// Define a custom class to gradually change a scene's background color
let change = SKAction.customActionWithDuration(duration) {
node, time in
let fraction = time * stepSize
let red = start.red * (1.0 - fraction) + end.red * fraction
let green = start.green * (1.0 - fraction) + end.green * fraction
let blue = start.blue * (1.0 - fraction) + end.blue * fraction
if let scene = node as? SKScene {
scene.backgroundColor = SKColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
return change
}
}

最后,创建并运行 SKAction
runAction(SKAction.changeColor(backgroundColor, endColor: SKColor.blueColor(), duration: 5))

将此添加到 didMoveToView在您的 SKScene子类,例如 GameScene .

关于sprite-kit - 将背景颜色淡化为另一种颜色的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938890/

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