Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an image node in SpriteKit? Swift 4

Somebody told me in one of my other questions that SpriteKit was easier than UI. I searched online on how to get started with SpriteKit, and I got this: https://www.raywenderlich.com/145318/spritekit-swift-3-tutorial-beginners. I put the images in and everything, I put this code in:

import SpriteKit

class GameScene: SKScene {

  // 1
  let player = SKSpriteNode(imageNamed: "player")
  override func didMove(to view: SKView) {
     // 2
     backgroundColor = SKColor.white
     // 3
     player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
     // 4
     addChild(player)
  }
}

(the code they told me to put in), and when I run it, I just see a blank screen. On the tutorial, it had a ninja, but mine is just a blank screen.

Can anyone help with this?

like image 387
Lunbun Avatar asked Mar 09 '18 04:03

Lunbun


1 Answers

if the screen is white try this :

import SpriteKit

class GameScene: SKScene {

  // 1
  var player = SKSpriteNode()
  override func didMove(to view: SKView) {
     // 2
     backgroundColor = SKColor.white
     // 3
     let image = UIImage(named: "player")
     let texture = SKTexture(image: image!)
     player = SKSpriteNode(texture: texture)
     player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
     // 4
     addChild(player)
  }
}

If the screen not white : make sure the scene presented correctly .

If you have the GameScene.sks :

In GameViewController :

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        let scene = SKScene(fileNamed: "GameScene")
        scene.scaleMode = .aspectFill
        view.presentScene(scene)

        view.ignoresSiblingOrder = true
        view.showsFPS = true
        view.showsNodeCount = true
    }
}

If you don't have GameScene.sks File

In GameViewController :

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        let scene = GameScene(size : view.frame.size)
        scene.scaleMode = .aspectFill
        view.presentScene(scene)

        view.ignoresSiblingOrder = true
        view.showsFPS = true
        view.showsNodeCount = true
    }
}
like image 110
mazen Avatar answered Dec 09 '22 11:12

mazen