gpt4 book ai didi

swift - 如何正确地为 SKSpriteNode 子类设置动画

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:34 45 4
gpt4 key购买 nike

我设计了一个 SKSpriteNode 子类 Ship,我想知道如何使用几个不同的图像来制作动画。我目前正在传递原始图像:

class Ship:SKSpriteNode{
static var shipImage = SKTexture(imageNamed:"Sprites/fullShip.png")

init(startPosition startPos:CGPoint, controllerVector:CGVector){
super.init(texture: Ship.shipImage, color: UIColor.clearColor(), size: Ship.shipImage.size())

但我不确定之后如何循环浏览图像图集。我首先尝试在类中使用一个方法,然后在 update 函数中调用该方法:

func animateShip() {
self.runAction(SKAction.repeatActionForever(
SKAction.animateWithTextures(shipAnimationFrames,
timePerFrame: 0.2,
resize: false,
restore: true)),
withKey:"shipBlink")

print("animate")
}

var shipAnimationFrames : [SKTexture]!GameScene 的正上方声明,这个 block 位于 didMoveToView

    //Ship animation
let shipAnimatedAtlas = SKTextureAtlas(named: "ShipImages")
var blinkFrames = [SKTexture]()

let numImages = shipAnimatedAtlas.textureNames.count
for var i=1; i<=numImages; i += 1 {
let shipTextureName = "samShip\(i).png"
blinkFrames.append(shipAnimatedAtlas.textureNamed(shipTextureName))
}

shipAnimationFrames = blinkFrames

任何帮助都会很棒!

最佳答案

纹理图集

首先,您需要在 Assets.xcassets 中创建纹理图集。您将在此处放置与您角色的框架相关的图像。

enter image description here

子类化 SKSpriteNode

这就是您使用 beginAnimation 方法创建自己的 Sprite 的方式

class Croc: SKSpriteNode {

init() {
let texture = SKTexture(imageNamed: "croc_walk01")
super.init(texture: texture, color: .clearColor(), size: texture.size())
}


func beginAnimation() {
let textureAtlas = SKTextureAtlas(named: "croc")
let frames = ["croc_walk01", "croc_walk02", "croc_walk03", "croc_walk04"].map { textureAtlas.textureNamed($0) }
let animate = SKAction.animateWithTextures(frames, timePerFrame: 0.1)
let forever = SKAction.repeatActionForever(animate)
self.runAction(forever)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

如您所见,beginAnimation 方法使用与我之前在 Assets.xcassets 中创建的纹理图集相同的名称创建纹理图集。

然后创建一组纹理()并将其用作创建animate Action 的参数。

开始动画

现在您需要创建 Sprite 并仅调用一次beginAnimation。您不必在任何更新方法中调用 beginAnimations,否则您将在每个新帧中创建一个新动画。错了。 beginAnimation 只能调用一次。

举个例子

class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let croc = Croc()
croc.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
addChild(croc)

croc.beginAnimation()
}
}

enter image description here

关于swift - 如何正确地为 SKSpriteNode 子类设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774980/

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