2014-09-06 86 views
4

我发现了一个使用objective-C在spritekit中进行视差滚动的教程,尽管我一直试图将它移植到swift中,但实际上却很少成功。视差滚动SpriteKit

Parallax Scrolling

没有人有任何其他教程或迅速做视差滚动的方法。

回答

4

这是一个启动视差背景的超简单方法。与SKACTIONS!我希望它能帮助你理解基础知识,然后再转向更难但更有效的编码方式。 所以我将从获得背景移动的代码开始,然后尝试复制前景中的代码或要放入场景中的对象。

//declare ground picture. If Your putting this image over the top of another image (use a png file). 
    var groundImage = SKTexture(imageNamed: "background.jpg") 

    //make your SKActions that will move the image across the screen. this one goes from right to left. 
    var moveBackground = SKAction.moveByX(-groundImage.size().width, y: 0, duration: NSTimeInterval(0.01 * groundImage.size().width)) 

    //This resets the image to begin again on the right side. 
    var resetBackGround = SKAction.moveByX(groundImage.size().width, y: 0, duration: 0.0) 

    //this moves the image run forever and put the action in the correct sequence. 
    var moveBackgoundForever = SKAction.repeatActionForever(SKAction.sequence([moveBackground, resetBackGround])) 

    //then run a for loop to make the images line up end to end. 
    for var i:CGFloat = 0; i<2 + self.frame.size.width/(groundImage.size().width); ++i { 
     var sprite = SKSpriteNode(texture: groundImage) 
     sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height/2) 
     sprite.runAction(moveBackgoundForever) 
     self.addChild(sprite) 
    } 
} 
//once this is done repeat for a forground or other items but them run at a different speed. 

/*确保您的照片在视觉上端对端排列。仅仅复制这段代码就不会像你所看到的那样工作,但它是一个起点。暗示。如果你的使用物品像简单的障碍物,然后使用动作来产生一个创建障碍物的功能也许是一个好方法。如果有多于两个单独的视差对象,那么为这些对象使用数组将有助于提高性能。有很多方法可以解决这个问题,所以我的观点很简单:如果你不能从ObjectiveC中移植它,那么在Swift中重新考虑它。祝你好运!

+0

不错 - 很简单。谢谢。把它变成了我传递背景名称,滚动速度和zPosition的函数。下一步它使背景成为可能的背景阵列,所以你可以让每一层不是来自一个图像和几个不同的图像。 – 2016-03-10 14:13:23