В настоящее время я создаю свое первое быстрое приложение с использованием UIKit. Я успешно запрограммировал все важные функции моей игры, но единственная проблема, с которой я столкнулся, - это задержка каждый раз, когда анимация загружается в сцену. Ниже мой код для отображения анимации. Мой вопрос: как лучше всего предотвратить задержку? Спасибо!
Создание стены и предварительная загрузка данных для анимации массива (непрерывно повторяется: каждый раз, когда объект размещается правильно) @ obj c fun c updateScene () {
leftWall.image = game.pickWalls()[0]
rightWall.image = game.pickWalls()[1]
bottomWall.image = game.pickWalls()[2]
game.resetwallcount()
shatterImages = createImagesArray(total: 26, imagePrefix: "Shatter", color: game.sprites[0].color[game.wallColorArray[0]]) //right
shatter2Images = createImagesArray(total: 26, imagePrefix: "Shatter", color: game.sprites[0].color[game.wallColorArray[1]]) //left
shatter1Images = createImagesArray(total: 23, imagePrefix: "Shatter1", color: game.sprites[0].color[game.wallColorArray[2]]) //bottom
}
Создает массив изображений и назначает цветовую забаву c createImagesArray (total: Int, imagePrefix: String, color: UIColor) - > [UIImage] {var imageArray: [UIImage] = []
for imageCount in 1..<total {
let imageName = "\(imagePrefix)-\(imageCount).png"
var image = UIImage(named: imageName)!
image = image.imageWithColor(color)!
imageArray.append(image)
}
return imageArray.compactMap({ $0 })
}
Создает новую анимацию с измененным цветом оттенка
extension UIImage {
func imageWithColor(_ color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
guard let context = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage else {
return nil }
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.clip(to: rect, mask: cgImage)
color.setFill()
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage
}
Анимирует массив
func animate(imageView: UIImageView, images: [UIImage]) {
imageView.animationImages = images
imageView.animationDuration = 0.7
imageView.animationRepeatCount = 1
imageView.startAnimating()
}
Определяет, правильно ли размещен объект и назначает анимация для правильно размещенного объекта
if self.game.correctValue == self.game.rightDiamondValue {
self.animate(imageView: self.rightGlass, images: self.shatterImages)
self.updateLabel()
} else {
self.gameOver()
}
}
if self.game.correctValue == self.game.bottomDiamondValue {
self.animate(imageView: self.bottomGlass, images: self.shatter1Images)
self.updateLabel()
} else {
self.gameOver()
}
}
if self.game.correctValue == self.game.leftDiamondValue {
self.animate(imageView: self.leftGlass, images: self.shatter2Images)
self.updateLabel()
} else {
self.gameOver()
}
}
Выберите цвет стен, с которым объект будет реагировать
mutating func pickWalls() -> [UIImage] {
while wallColorSet.count < 3 {
randomIndex = colorArray.randomElement()!
wallColorSet.insert(sprites[0].correctValue[randomIndex])
print(randomIndex)
}
wallColorArray = Array(wallColorSet)
wallArray = [sprites[0].wall[wallColorArray[0]], sprites[0].wall[wallColorArray[1]], sprites[0].bottomWall[wallColorArray[2]]]
//wallArray = Array(wallSet)
//wallArray[2] = sprites[0].bottomWall[randomIndex]
return wallArray
}
Сбрасывает цвета стен на ноль
mutating func resetwallcount() -> Set<Int> {
wallColorSet = Set<Int>()
return wallColorSet
}