Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace level button image with a screenshot of the level game scene?

I know how to take and save a screenshot to the photo library. I do this using the code below. I would like to replace my level scene button images with screenshots of my gameScene. Say my image buttons are 150x150. How can I achieve this?

    func takeScreenShot(scene:SKScene)  {
    let bounds = self.scene!.view?.bounds
    UIGraphicsBeginImageContextWithOptions(/*CGRect(x: 0, y: 0, width: 100, height: 100).size*/bounds!.size, true, UIScreen.main.scale)
    self.scene?.view?.drawHierarchy(in: bounds!, afterScreenUpdates: true)
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil)

}


class LevelSelectScene: SKScene {

let button1: SKSpriteNode = SKSpriteNode(imageNamed: "image1")
let button2: SKSpriteNode = SKSpriteNode(imageNamed: "image2")
let button3: SKSpriteNode = SKSpriteNode(imageNamed: "image3")

                    ...

override init(size: CGSize){
super.init(size: size)

button1.position = CGPoint(x: self.frame.width/4, y:  self.frame.height/2)
self.addChild(button1)

button2.position = CGPoint(x: self.frame.width/2, y:  self.frame.height/2)
self.addChild(button2)

button3.position = CGPoint(x: 3*self.frame.width/4, y:  self.frame.height/2)
self.addChild(button3)

}
like image 206
Hilarious404 Avatar asked Apr 06 '17 05:04

Hilarious404


People also ask

How do you change a scene with a button?

Click on the "File" menu in the menu bar. Select the build settings, switch the platform, and add an Open scene select. Click on the Play button. Select change Scene on Button click.

How do you change from one scene to another in Unity?

Loading a new game scene is an easy way to change between levels or other in game menus. To get started, simply go to the file tab and select new scene. Be sure to save the current game scene if prompted.

What are .Unity files?

File created by Unity, a 3D engine primarily used to create video games; contains a unique level within a 3D game that includes objects, environments, decorations, cameras, lighting, and obstacles; used with other scenes to build a virtual world when editing.


1 Answers

As UIGraphicsGetImageFromCurrentImageContextreturns a UIImage, and SKTexture has an initiaser that takes a UIImage, and SKSpriteNode (which I assume you are using for your button) has an initialiser that takes an SKTexture and a CGSize, I think you have everything you need:

if let screenshot = UIGraphicsGetImageFromCurrentImageContext() {
   let screenShotTexture = SKTexture(image: screenshot) 
   let button = SKSpriteNode(texture: screenShotTexture, size: CGSize(width: 150, height: 150))
}

Using this, you wouldn't need to save the screenshot to the photo album (unless you wanted to for other reasons).

like image 174
Steve Ives Avatar answered Oct 31 '22 17:10

Steve Ives