如何在 swift 中执行一个函数 5 秒
How to execute a function for 5 seconds in swift
我正在创建一个游戏,此功能用作缩小精灵的电源。我希望这个函数执行 5 秒,并将这个 5 秒计时器附加到标签上作为倒计时。
函数结束后,return精灵恢复到原来的大小。
函数只是通过设置比例来缩小节点。
func shrinkShip() { spaceShip.scale(to: CGSize(width: 60, height: 40)) }
您可以像这样为视图设置动画:
UIView.animate(withDuration: 5, animations: {
self.spaceShip.scale(to: CGSize(width: 60, height: 40))
},
completion: { _ in
UIView.animate(withDuration: 2) {
self.spaceShip.transform = .identity // Reset your view
}
})
你可以试试这样的
UIView.animate(withDuration: 5, animations: {
self.spaceShip.transform = CGAffineTransform(scaleX: 60, y: 40)
},
completion: { _ in
UIView.animate(withDuration: 2) {
self.spaceShip.transform = .identity // Reset your view
}
})
坚持使用 SpriteKit 我会做以下事情
func shrinkShip(duration: Double) {
let originalSize = spaceShip.size
spaceShip.scale(to: CGSize(width: 60, height: 40))
for x in 0..<Int(duration) {
//increment the timer every 1 second for the duration
self.run(SKAction.wait(forDuration: 1 * Double(x))) {
self.timerLabel.text = String(Int(duration) - x)
}
}
self.run(SKAction.wait(forDuration: duration)) {
//return the spaceship to full size
self.spaceShip.scale(to: originalSize)
//hide the timer
self.timerLabel.text = ""
self.timerLabel.isHidden = true
}
}
我正在创建一个游戏,此功能用作缩小精灵的电源。我希望这个函数执行 5 秒,并将这个 5 秒计时器附加到标签上作为倒计时。 函数结束后,return精灵恢复到原来的大小。
函数只是通过设置比例来缩小节点。
func shrinkShip() { spaceShip.scale(to: CGSize(width: 60, height: 40)) }
您可以像这样为视图设置动画:
UIView.animate(withDuration: 5, animations: {
self.spaceShip.scale(to: CGSize(width: 60, height: 40))
},
completion: { _ in
UIView.animate(withDuration: 2) {
self.spaceShip.transform = .identity // Reset your view
}
})
你可以试试这样的
UIView.animate(withDuration: 5, animations: {
self.spaceShip.transform = CGAffineTransform(scaleX: 60, y: 40)
},
completion: { _ in
UIView.animate(withDuration: 2) {
self.spaceShip.transform = .identity // Reset your view
}
})
坚持使用 SpriteKit 我会做以下事情
func shrinkShip(duration: Double) {
let originalSize = spaceShip.size
spaceShip.scale(to: CGSize(width: 60, height: 40))
for x in 0..<Int(duration) {
//increment the timer every 1 second for the duration
self.run(SKAction.wait(forDuration: 1 * Double(x))) {
self.timerLabel.text = String(Int(duration) - x)
}
}
self.run(SKAction.wait(forDuration: duration)) {
//return the spaceship to full size
self.spaceShip.scale(to: originalSize)
//hide the timer
self.timerLabel.text = ""
self.timerLabel.isHidden = true
}
}