如何在Swift Playgrounds中使用带纹理的SKNode设置SKScene?

时间:2017-03-13 15:50:15

标签: swift sprite-kit swift-playground

我尝试将模板代码从SpriteKit项目复制到一个游乐场,但是当我呈现场景时,我得到的只是灰色屏幕。我是否需要创建SKScene,如果是,我如何将其分配给我正在使用的场景类。

以下是我创建和呈现场景的代码:

 @objc func goToGameScene(){

    print("GameView Loaded")

 sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 666, height: 500))



sceneView.backgroundColor = UIColor.black

PlaygroundPage.current.liveView = sceneView

if let view = self.sceneView as SKView? {
    // Load the SKScene from 'GameScene.sks'
    if let scene = SKScene(fileNamed: "GameScene") {
        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill

        // Present the scene
        view.presentScene(scene)
    }

    view.ignoresSiblingOrder = true


}

这是我的SKScene类,其文件名为GameScene.swift。

import Foundation
import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {
var bg = SKSpriteNode()
func didBegin(_ contact: SKPhysicsContact) {
}
override func didMove(to view: SKView) {
    self.physicsWorld.contactDelegate = self
    let bgTexture = SKTexture(image: UIImage(named: "MainScreenBackground.png")!)
    let moveBGAnimation = SKAction.move(by: CGVector(dx:-bgTexture.size().width, dy:0), duration: 11)
    let shiftBackground = SKAction.move(by: CGVector(dx: bgTexture.size().width, dy:0), duration: 0)
    let repeatAnimationBg = SKAction.repeatForever(SKAction.sequence([moveBGAnimation, shiftBackground]))
    var q = 0
    while(q < 3){
        bg = SKSpriteNode(texture: bgTexture)
        bg.position = CGPoint(x:  bgTexture.size().width * CGFloat(q), y: self.frame.midY)
        bg.size.height = self.frame.height
        bg.run(repeatAnimationBg)
        self.addChild(bg)
        q+=1
        bg.zPosition = -1
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
}
}

1 个答案:

答案 0 :(得分:1)

假设您已将MainScreenBackground.png图片拖放到Assets.xcassets文件夹中,可以使用以下代码将图片作为SKSpriteNode添加到场景中。

override func didMove(to view: SKView) {
    self.physicsWorld.contactDelegate = self
    let bgTexture = SKSpriteNode(imageNamed: "MainScreenBackground")
    self.addChild(bgTexture)
    ...