Where ist the error in the Swift-Code?(Sprite-Kit)

I would like to program a game with a SKVideoNode. I looked for a tutorial but all Codes were wrong . Here is one of them:




import SpriteKit

import AVFoundation

class GameScene: SKScene {

let sample = SKVideoNode(fileNamed: "Video")

sample.position = CGPoint(x: frame.midX,y: frame.midY). EXPECTED DECLARATION

addChild(sample)

sample.play()

}



Please don´t laugh at me bacause mI am a beginner.

Replies

The problem is that your code structure is incorrect. In this code, you are defining a subclass of SKScene, with this structure:


class GameScene: SKScene {
     …
}


What goes inside the curly brackets is a series of declarations, not code (statements). That's why the compiler is telling you it expected a declaration.


So, you need to place the above code inside a declared method (function). Based on your existing code, it looks like your intention is to run this code when an instance of the GameScene class is created and initialized, so the code needs to go in an initializer:


class GameScene: SKScene {
     override init (size: CGSize) {
          let sample = SKVideoNode(fileNamed: "Video")
          sample.position = CGPoint(x: frame.midX,y: frame.midY)
          addChild(sample)
          sample.play()
     }
}


However, there are more things that need your attention here:


— You need to learn about coordinate systems. The "frame" property of the scene is in the coordinate system of its parent, while the "position" property of its child "sample" node is in the scene's own coordinate system. Your code will probably work for now (the two coordinate systems are initially the same), but may break in the future.


There is a lot information about this and other scene-related topics here:


developer.apple.com/reference/spritekit/skscene


— It's possibly not a good idea to start the video playing in this place. Initialization is part of a larger setup process, and staring the video too early may cause it to compete with other activity, so it may start out jerky, or appear to freeze for a while. It might be better to override (for example) the scenes "didMove(to:)" method and start it there, or delay the start of video playback in some other way.


Still, it's OK to try it like you have it, and see what happens.