Created
February 14, 2019 16:02
-
-
Save Fedenieto90/3cab9cd82d80039c3ecd569b0398bd80 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Creates A Video Player As An SCNGeometries Diffuse Contents | |
static func setupVideoOnNode(_ node: SCNNode, fromURL url: URL) { | |
//1. Create An SKVideoNode | |
var videoPlayerNode: SKVideoNode! | |
//2. Create An AVPlayer With Our Video URL | |
let videoPlayer = AVPlayer(url: url) | |
//3. Initialize The Video Node With Our Video Player | |
videoPlayerNode = SKVideoNode(avPlayer: videoPlayer) | |
videoPlayerNode.yScale = -1 | |
//4. Create A SpriteKitScene & Position It | |
let spriteKitScene = SKScene(size: CGSize(width: 1024, height: 768)) | |
spriteKitScene.scaleMode = .aspectFit | |
videoPlayerNode.position = CGPoint(x: spriteKitScene.size.width/2, y: spriteKitScene.size.height/2) | |
videoPlayerNode.size = spriteKitScene.size | |
spriteKitScene.backgroundColor = .clear | |
//5. Alpha transparency | |
let effectNode = getAlphaEffectNode(videoPlayerNode: videoPlayerNode) | |
spriteKitScene.addChild(effectNode) | |
effectNode.addChild(videoPlayerNode) | |
//6. Set The Nodes Geoemtry Diffuse Contenets To Our SpriteKit Scene | |
node.geometry?.firstMaterial?.diffuse.contents = spriteKitScene | |
//7. Play The Video | |
videoPlayerNode.play() | |
videoPlayer.volume = 0 | |
//8. Loop Video | |
loopVideo(videoPlayer: videoPlayer, node: node) | |
} | |
// MARK: - Add Alpha Transparency | |
static func getAlphaEffectNode(videoPlayerNode: SKVideoNode) -> SKEffectNode { | |
// Let's make it transparent, using an SKEffectNode, | |
// since a shader cannot be applied to a SKVideoNode directly | |
let effectNode = SKEffectNode() | |
effectNode.shader = EffectNodeHelper.getAlphaShader() | |
return effectNode | |
} | |
// MARK: - Loop Video | |
static func loopVideo(videoPlayer: AVPlayer, node: SCNNode) { | |
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, | |
object: videoPlayer.currentItem, | |
queue: nil) { (_) in | |
videoPlayer.seek(to: kCMTimeZero) | |
videoPlayer.play() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment