2016-10-14 3 views
4

視認可能な画像セクションを等速度で右に移動/スクロールするアニメーションを作成するにはどうすればよいですか? OR OR:UIScrollViewを右にアニメートする方法は?UIScrollViewを右にアニメ化する

例:画像の幅は4968ピクセルです。画像は、フルスクリーンの背景画像として使用されます。 4968pxの最初の1242px(画像幅)のみが最初に見えるはずです。見ることのできる画像セクションは、均一な速度で右に動くはずです。いつでも、画像の1242ピクセルが表示されます。イメージの終わりに達すると、このプロセスは反復されるべきです。

Visualisation of my question

ここに私のコードは、これまでのところです。私が達成したいことが不完全であることを理解することは有用ではありませんが、関数更新などで使用したことがわかります。

override func update(_ currentTime: TimeInterval) { 
    if gameStarted == true { 
     enumerateChildNodes(withName: "background", using: ({ 
      (node, error) in 

      let bg = node as! SKSpriteNode 

      bg.position = CGPoint(x: bg.position.x - 2, y: bg.position.y) 
      } 
     })) 
    } 
} 

答えて

2

をアニメーション化することができます。

しかし、スムーズに反復するには、その時点で2つの画像を保持する必要があります。

var imageWidth : Float = 4968 
var viewPortWidth : Float = 1242 
var velocity : Float = 10 
var currentNodeIndex : Int = 0 
let backgrounds : [String] = ["background0", "background1"] 
var currentNodeName : String { 
    get { 
     return backgrounds[currentNodeIndex] 
    } 
} 

func setup() { 
    node : SKNode = SKSpriteNode(imageNamed:"backgroundImage") 
    node.name = "background0" 
    node1 : SKNode = SKSpriteNode(imageNamed:"backgroundImage") 
    node1.name = "background1" 
    addChild(node) 
    addChild(node1) 
    node.position = CGPoint(x: imageWidth, y: 0) 
    node1.position = CGPoint(x: 0, y: 0) 
} 

override func update(_ currentTime: TimeInterval) { 
    if gameStarted == true { 
     backgrounds.forEach { 
      enumerateChildNodes(withName: $0, using: {(node, error) in 
       node.position = CGPoint(x: node.position.x - velocity, y: node.position.y) 
      }) 
     } 
    } 
} 

private func rollImageAroundIfNeeded() { 
    if needsRollImages() { 
     rollImagesAround() 
    } 
} 

private func needsRollImages() -> Bool { 
    node : SKNode = childNode(withName:currentNodeName)! 
    return node.position.x < 2 * (screenWidth - imageWidth) 
} 

private func rollImageAround() { 
    node : SKNode = childNode(withName:currentNodeName)! 
    node.position = CGPoint(x: node.position.x + 2 * imageWidth, y: node.position.y) 
    currentNodeIndex = (currentNodeIndex + 1) % 2 
} 

イメージの位置を左に連続して移動し、ある閾値では左のイメージを右に「ラップ」するという考えがあります。

+0

素晴らしい解決策、位置の変更は最初の画像でうまく機能します。 "rollImageAroundIfNeeded"関数が実行されていません。答えを編集できますか? –

2

あなたは、あなたが一定の速度で移動するゲームの背景を持っているしたい場合は、全くUIScrollViewを必要としないそのcontentOffsetプロパティ

@IBOutlet weak var scrollView: UIScrollView! 

override func viewDidAppear(animated: Bool) { 
    // This code scrolls to the point (x: 4000, y:0) in 5 seconds 
    UIView.animateWithDuration(5) { [unowned self] in 
     self.scrollView.contentOffset = CGPoint(x: 4000, y: 0) 
    } 
} 
+1

これは、OPに対する少し不完全な回答です。 1)OPは継続的な反復スクロールを要求します。 2)OPは均一速度を要求し、 '' [UIView animateWithDuration] '' 'はデフォルトで緩和します 3)これはユーザのスクロールを防ぎません –

関連する問題