SKSpriteNode Not Loading Onto Screen? - swift

Everything works fine,but then when I add the apple,it only stays on screen for a very short amount of time, and then it goes away/disappears. Why is this? any help would be much appreciated.
import SpriteKit
class GameScene: SKScene {
var bg=SKSpriteNode()
var apple=SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let bg_texture=SKTexture(imageNamed: "wood-texture-pattern.jpg")
bg=SKSpriteNode(texture: bg_texture)
bg.position=CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bg.size.height=self.frame.height
bg.size.width=self.frame.width
self.addChild(bg)
let applePic=SKTexture(imageNamed:"apple.png")
apple=SKSpriteNode(texture:applePic)
apple.position=CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
// apple.size.height=50
// apple.size.width=50
apple.setScale(0.25)
self.addChild(apple)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}

Change the zPosition of the skspritenode

Related

How to access the events and elements inside a SpriteKit GameScene?

I'm new to SpriteKit and starting to collect some experience.
What I currently can not understand is how to mix a GameScene with my own code?
So, there is a way to do all manually like this:
class GameScene: SKScene {
override func didMove(to view: SKView) {
//...
}
override func update(_ currentTime: TimeInterval) {
//...
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//...
}
}
And then pass it to my SpriteView:
SpriteView(scene: GameScene())
This is fine, so I can do everything in Swift by code. To use a .sks GameScene file its also easy by using:
SpriteView(scene: SKScene(fileNamed: "MyScene")!)
BUT what I need to do to override the methods in MyScene and access the Sprites I created via the editor?
I found it in the example. I can use the Custom Class property in the .sks file

Adding button to GameScene.swift programatically and transitioning scenes when pressed

I have been working forever trying to implement a way to add a button and when pressed the scene transitions to my second view. I have read other posts but have had ZERO luck for something in Swift 3. I'm really confused and have tried but failed many times. Hope you can help! Thanks!
Swift 3 in SpriteKit.
What do you mean transition to a new view?. When making SpriteKit games we tend to transition between SKScenes and not views. So do not try to create different views or viewControllers for each scene, just transition between SKScenes directly.
In regards to buttons, there is plenty tutorials available. You basically create a SKSpriteNode as a button and look for it in touchesBegan and do something when its pressed.
This is a simple example here
https://nathandemick.com/2014/09/buttons-sprite-kit-using-swift/
Essential you can create a button subclass similar to this.
class Button: SKNode {
let defaultButton: SKSpriteNode
let activeButton: SKSpriteNode
var action: () -> ()
init(defaultButtonImage: String, activeButtonImage: String, buttonAction: #escaping () -> ()) {
defaultButton = SKSpriteNode(imageNamed: defaultButtonImage)
activeButton = SKSpriteNode(imageNamed: activeButtonImage)
activeButton.isHidden = true
action = buttonAction
super.init()
isUserInteractionEnabled = true
addChild(defaultButton)
addChild(activeButton)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
activeButton.isHidden = false
defaultButton.isHidden = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
activeButton.isHidden = false
defaultButton.isHidden = true
} else {
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if defaultButton.contains(location) {
action()
}
activeButton.isHidden = true
defaultButton.isHidden = false
}
}
}
and than in your relevant SKScene add your buttons
class StartScene: SKScene {
override func didMove(to view: SKView) {
let playButton = Button(defaultButtonImage: "button", activeButtonImage: "button_active", buttonAction: loadGameScene)
playButton.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(playButton)
}
func loadGameScene() {
let scene = GameScene(...)
let transition = SKTransition....
scene.scaleMode = .aspectFill
view?.presentScene(scene, transition: transition)
}
}
You can also check out Apples sample game DemoBots for another button class example using protocols.
Hope this helps

tvOS pressesBegan() not updating in GameScene

In my GameScene, when I update variables using 'touchesBegan()' it works fine, but when I pass 'pressesBegan()' from the GameViewController to the GameScene, the code gets excited, but the changes get ignored.
GameViewController:
class GameViewController: UIViewController {
...
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
let scene = GameScene(fileNamed: "GameScene")
scene?.pressesBegan(presses, withEvent: event)
}
GameScene:
class GameScene: SKScene {
var test = true
...
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
test = false
print(test)
}
override func update(currentTime: CFTimeInterval) {
print(test)
}
}
This code will result in "false" then "true" in the console.
Every time you call pressesBegan, you are creating a new Gamescene, you need to do
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
if let skView = self.view as? SKView
{
skView.scene?.pressesBegan(presses, withEvent: event)
}
}

How to create background that follows the character in SWIFT?

I am working on this project in Xcode, where I am making animations. I have perfectly working program where little character walks around the screen. If I press on screen, that is direction the character is going. What I want to do here is to add a background image and make it follow where character is going. Basically, I want character to be able to walk around big map while he does not go out of the image. Something like scrollView, but only in gamescene.
P.S. All the code below is working, I just want to add the background image that moves along.
Here is some code for my main gamescene
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// the hero is initialized with a texture
hero = Player(named: "hero_walk_down_0")
hero.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(hero)
if Settings.sharedInstance.virtualPad {
controller = ControllerNode(position: CGPoint(x:0, y: 0))
self.addChild(controller)
}
backgroundColor = SKColor.blueColor()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if Settings.sharedInstance.virtualPad == false {
hero.destination = location
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let previousLocation = touch.previousLocationInNode(self)
if Settings.sharedInstance.virtualPad == false {
hero.destination = location
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
touchesEndedOrCancelled(touches, withEvent: event)
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
touchesEndedOrCancelled(touches, withEvent: event)
}
func touchesEndedOrCancelled(touches: NSSet, withEvent event: UIEvent) {
// when a touch is ended, remove it from the list
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let previousLocation = touch.previousLocationInNode(self)
if Settings.sharedInstance.virtualPad == false {
hero.destination = nil
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if Settings.sharedInstance.virtualPad {
hero.walk(self.controller!.pressedDirections())
}
else {
if hero.destination != nil {
hero.walkTowards(hero.destination!)
}
}
}
You create two SKNodes - one for the character and one for the background and add them to each group separately.
Whenever you move the SKNode of the character, you replicate the same action on the background node.

SKSpriteNode not detecting touch events

I can not get the touchesBegan function to fire. It isn't being called when a user touched the node.
import SpriteKit
class SimpleButton: SKSpriteNode {
//called when the user taps the button
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
println("touches began")
}
//called when the user finishes touching the button
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
println("touches ended")
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
println("touches moved")
}
}
The answer is, You need to enable touches using the userInteractionEnabled parameter.
let imageTexture = SKTexture(imageNamed: "a_button")
let sprite: SimpleButton = SimpleButton(texture: imageTexture)
sprite.userInteractionEnabled = true // <--- This is required, it defaults to false.
sprite.position = CGPoint(x:CGRectGetMidX(self.frame) - 200, y:CGRectGetMidY(self.frame));
sprite.color = UIColor.blackColor()
sprite.colorBlendFactor = 1.0
self.addChild(sprite)