I tried copying the template code from a SpriteKit project into a playground, but all I get is a grey screen when I present the Scene. Do I need to create an SKScene and if so how do I assign it to the scene class that I am using.
我尝试将SpriteKit项目中的模板代码复制到一个游乐场,但当我呈现场景时,得到的只是一个灰色的屏幕。我是否需要创建一个SKScene,如果需要,我如何将它分配给我正在使用的scene类。
The following is my code to create and present the scene:
以下是我创建和呈现场景的代码:
@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
}
And this is my SKScene class, which has a filename of GameScene.swift.
这是我的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 个解决方案
#1
1
Assuming you have dragged and dropped your MainScreenBackground.png
image into you Assets.xcassets
folder, you can use the code below to add the image to your scene as a SKSpriteNode
.
假设您拖拽并删除了主屏幕背景。png图像到您的资产。xcassets文件夹,您可以使用下面的代码将图像添加到场景中作为SKSpriteNode。
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
let bgTexture = SKSpriteNode(imageNamed: "MainScreenBackground")
self.addChild(bgTexture)
...
#1
1
Assuming you have dragged and dropped your MainScreenBackground.png
image into you Assets.xcassets
folder, you can use the code below to add the image to your scene as a SKSpriteNode
.
假设您拖拽并删除了主屏幕背景。png图像到您的资产。xcassets文件夹,您可以使用下面的代码将图像添加到场景中作为SKSpriteNode。
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
let bgTexture = SKSpriteNode(imageNamed: "MainScreenBackground")
self.addChild(bgTexture)
...