【问题标题】:How to set up an SKScene with an SKNode with a texture in Swift Playgrounds?如何在 Swift Playgrounds 中使用带有纹理的 SKNode 设置 SKScene?
【发布时间】:2017-03-13 15:50:14
【问题描述】:

我尝试将 SpriteKit 项目中的模板代码复制到 Playground 中,但是当我呈现场景时,我得到的只是一个灰屏。我是否需要创建一个 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) {
}
}

【问题讨论】:

    标签: swift sprite-kit swift-playground


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-03
      • 2020-04-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多