我有一个分支的矢量图,上面有几片叶子。我正在将分支从屏幕底部移动到屏幕顶部。但是,当分支从初始位置(屏幕底部)移动到最终位置(屏幕顶部)时,我希望分支在移动到顶部时从绿色变为橙色。这应该是一个平稳的过渡。我有树枝和树叶作为矢量图像。我正在使用spritekit(ios)进行开发。该分支已附加在下面的链接中 我不希望颜色立即从绿色变为红色。我希望它随着分支移到顶部而从绿色逐渐过渡到红色
答案 0 :(得分:1)
您将需要2张图像,绿色一张
和红色的。
现在您需要一个节点来保存两个图像
class Element: SKNode {
private let green = SKSpriteNode(imageNamed: "green")
private let red = SKSpriteNode(imageNamed: "red")
override init() {
super.init()
self.addChild(green)
red.alpha = 0
self.addChild(red)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func turnRed(duration: TimeInterval) {
green.run(.fadeOut(withDuration: duration))
red.run(.fadeIn(withDuration: duration))
}
}
最后,您只需要调用turnRed(duration:)
方法
class GameScene: SKScene {
let element = Element()
override func didMove(to view: SKView) {
self.addChild(element)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// move the element to bottom
let bottomY = self.frame.minY + element.calculateAccumulatedFrame().height / 2
let moveToBottom = SKAction.moveTo(y: bottomY, duration: 2)
element.run(moveToBottom)
// change the color
element.turnRed(duration: 2)
}
}
如果要以绿色和红色之间的给定比例设置颜色,请使用以下代码
class Element: SKNode {
private let green = SKSpriteNode(imageNamed: "green")
private let red = SKSpriteNode(imageNamed: "red")
override init() {
super.init()
self.addChild(green)
red.alpha = 0
self.addChild(red)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// colorProgressionRatio must be a value between 1 (full green) and 0 (full red)
func update(colorProgressionRatio: CGFloat) {
guard colorProgressionRatio >= 0 && colorProgressionRatio <= 1 else {
debugPrint("colorProgressionRatio must be a value between 0 and 1")
return
}
let greenIntensity: CGFloat
let redIntensity: CGFloat
if colorProgressionRatio == 0 {
greenIntensity = 0
redIntensity = 1
} else if colorProgressionRatio == 1 {
greenIntensity = 1
redIntensity = 0
} else {
greenIntensity = colorProgressionRatio
redIntensity = 1 - colorProgressionRatio
}
green.run(.fadeAlpha(to: greenIntensity, duration: 2))
red.run(.fadeAlpha(to: redIntensity, duration: 2))
}
}
现在您只需要打电话
element.update(colorProgressionRatio: 0.4)
传递0到1之间的值(0表示红色,1表示全绿色)。