Sprite kit 精灵套件旋转重复

Sprite kit 精灵套件旋转重复,sprite-kit,swift2,Sprite Kit,Swift2,你如何使一个精灵像船一样不断地来回摆动 下面是我写的代码: import UIKit import SpriteKit let boat = SKSpriteNode(imageNamed: "boat_floor") var rotationVal = CGFloat(-1) class GameScene: SKScene { override func didMoveToView(view: SKView) { backgroundColor = UIColor.whiteCol

你如何使一个精灵像船一样不断地来回摆动

下面是我写的代码:

import UIKit
import SpriteKit

let boat = SKSpriteNode(imageNamed: "boat_floor")
var rotationVal = CGFloat(-1)
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
    backgroundColor = UIColor.whiteColor()
    boat.size = CGSize(width: self.frame.size.width, height: self.frame.size.width)
    boat.position = CGPoint(x: self.frame.size.width/2, y: 0)
    boat.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "boat_floor"), size: boat.size)
    boat.physicsBody?.dynamic = false
    boat.alpha = 1
    self.addChild(boat)
    ChangeAngle()
    NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: Selector("ChangeAngle"), userInfo: nil, repeats: true)
}
func ChangeAngle(){
    let action = SKAction.rotateByAngle(rotationVal, duration:30)
    if rotationVal < 0 {
        rotationVal = CGFloat(M_PI)
        boat.runAction(action)
    }
    else if rotationVal > 0 {
        rotationVal = -CGFloat(M_PI)
        boat.runAction(action)
    }
    print(rotationVal)


}

}
导入UIKit
进口SpriteKit
let boat=SKSpriteNode(图像名称为:“船底”)
var rotationVal=CGFloat(-1)
类游戏场景:SKScene{
覆盖func didMoveToView(视图:SKView){
backgroundColor=UIColor.whiteColor()
boat.size=CGSize(宽度:self.frame.size.width,高度:self.frame.size.width)
boat.position=CGPoint(x:self.frame.size.width/2,y:0)
boat.physicsBody=SKPhysicsBody(纹理:SKTexture(图像名称:“boat_floor”),大小:boat.size)
boat.physicsBody?.dynamic=false
船α=1
赛尔夫·阿德奇尔德(船)
ChangeAngle()
scheduledTimerWithTimeInterval(3,目标:self,选择器:选择器(“ChangeAngle”),userInfo:nil,repeats:true)
}
func ChangeAngle(){
let action=SKAction.rotateByAngle(rotationVal,持续时间:30)
如果旋转值<0{
rotationVal=CGFloat(μPI)
快艇,快艇,快艇
}
如果rotationVal>0,则为else{
旋转值=-CGFloat(M_PI)
快艇,快艇,快艇
}
打印(旋转值)
}
}

如果我理解正确,您可以这样做(只需复制并粘贴代码即可查看其工作原理):

在SpriteKit中使用NSTimer通常是个坏主意,因为它不考虑节点、场景或视图的暂停状态

import UIKit
import SpriteKit

let boat = SKSpriteNode(color: SKColor.greenColor(), size:CGSize(width: 200, height: 80))


class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        backgroundColor = UIColor.whiteColor()

        boat.position = CGPoint(x: self.frame.size.width/2, y: 100)

        boat.alpha = 1
        self.addChild(boat)


        let rotate = SKAction.rotateByAngle(-0.6, duration:4)

        let sequence = SKAction.repeatActionForever(SKAction.sequence([rotate, rotate.reversedAction()]))

        let complete = SKAction.sequence([SKAction.rotateByAngle(0.3, duration:2), sequence])

        boat.runAction(complete, withKey:"someKey")

    }

}