Child objects not appearing in Index order - swift

Any ideas as to why my Sprites aren't appearing in the correct order here? The snowflake shows up at index 0 instead of 1.
Even if I switch the order around, the snowflake still appears behind everything else.
import Foundation
import SpriteKit
class page1: SKScene {
let background = SKSpriteNode(imageNamed: "01_BG")
let snowflake = SKSpriteNode(imageNamed: "home_snowflake02")
let room = SKSpriteNode(imageNamed: "01_room")
let kid = SKSpriteNode(imageNamed: "01_kidStanding")
override init(size: CGSize){
super.init(size: size)
}
override func didMoveToView(view: SKView) {
//Set up background
background.position = CGPoint(x: 200, y: 380)
background.xScale = 1.0
background.yScale = 1.0
insertChild(background, atIndex: 0)
//Set up Snowflakes
snowflake.position = CGPoint(x: 250, y: 1100)
snowflake.xScale = 1.0
snowflake.yScale = 1.0
insertChild(snowflake, atIndex: 1)
//Set up room
room.position = CGPoint(x: 512, y: 384)
room.xScale = 1.0
room.yScale = 1.0
insertChild(room, atIndex: 2)
//Set up kid
kid.position = CGPoint(x: 320, y: 290)
kid.xScale = 1.0
kid.yScale = 1.0
insertChild(kid, atIndex: 3)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

If your scenes view has it's ignoresSiblingOrder property set to true, performance can be improved but the order of sibling sprites is unreliable.
You can set a sprites zPosition directly to deal with this.
eg:
background.zPosition = 0
snowflake.zPosition = 1
or
snowflake.zPosition = background.zPosition + 1
to keep it relative to a sibling.

Related

Change color gradient around donut view

I am trying to make an animated donut view that when given a value between 0 and 100 it will animate round the view up to that number. I have this working fine but want to fade the color from one to another, then another on the way around. Currently, when I add my gradient it goes from left to right and not around the circumference of the donut view.
class CircleScoreView: UIView {
private let outerCircleLayer = CAShapeLayer()
private let outerCircleGradientLayer = CAGradientLayer()
private let outerCircleLineWidth: CGFloat = 5
override init(frame: CGRect) {
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
buildLayers()
}
/// Value must be within 0...100 range
func setScore(_ value: Int, animated: Bool = false) {
if value != 0 {
let clampedValue: CGFloat = CGFloat(value.clamped(to: 0...100)) / 100
if !animated {
outerCircleLayer.strokeEnd = clampedValue
} else {
let outerCircleAnimation = CABasicAnimation(keyPath: "strokeEnd")
outerCircleAnimation.duration = 1.0
outerCircleAnimation.fromValue = 0
outerCircleAnimation.toValue = clampedValue
outerCircleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
outerCircleLayer.strokeEnd = clampedValue
outerCircleLayer.add(outerCircleAnimation, forKey: "outerCircleAnimation")
}
outerCircleGradientLayer.colors = [Constant.Palette.CircleScoreView.startValue.cgColor,
Constant.Palette.CircleScoreView.middleValue.cgColor,
Constant.Palette.CircleScoreView.endValue.cgColor]
}
}
private func buildLayers() {
// Outer background circle
let arcCenter = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let startAngle = CGFloat(-0.5 * Double.pi)
let endAngle = CGFloat(1.5 * Double.pi)
let circlePath = UIBezierPath(arcCenter: arcCenter,
radius: (frame.size.width - outerCircleLineWidth) / 2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
// Outer circle
setupOuterCircle(outerCirclePath: circlePath)
}
private func setupOuterCircle(outerCirclePath: UIBezierPath) {
outerCircleLayer.path = outerCirclePath.cgPath
outerCircleLayer.fillColor = UIColor.clear.cgColor
outerCircleLayer.strokeColor = UIColor.black.cgColor
outerCircleLayer.lineWidth = outerCircleLineWidth
outerCircleLayer.lineCap = CAShapeLayerLineCap.round
outerCircleGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
outerCircleGradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
outerCircleGradientLayer.frame = bounds
outerCircleGradientLayer.mask = outerCircleLayer
layer.addSublayer(outerCircleGradientLayer)
}
}
I am going for something like this but the color isn't one block but gradients around the donut view from one color to the next.
If you imported AngleGradientLayer into your project then all you should need to do is change:
private let outerCircleGradientLayer = CAGradientLayer() to
private let outerCircleGradientLayer = AngleGradientLayer()

Sprite is missing on scene

I'm new in Sprite Kit and I have a strange problem with my GameScene. Can't figure out, what causes the problem. I present my scene from controller in viewWillAppearMethod in this way:
let atlas = SKTextureAtlas(named: "Sprites")
atlas.preload { [unowned self] in
DispatchQueue.main.async {
self.gameScene = GameScene(level: self.level, size: self.gameSKView!.bounds.size)
self.gameScene.scaleMode = .resizeFill
self.gameSKView?.presentScene(self.gameScene)
self.gameSKView?.ignoresSiblingOrder = true
self.gameSKView?.showsNodeCount = true
}
}
My sprite atlas content looks like: link
Than i create my spaceship:
final class SpaceshipSpriteNode: SKSpriteNode {
required init(size: CGSize) {
let texture = SKTexture(image: #imageLiteral(resourceName: "Spaceship"))
super.init(texture: texture, color: .white, size: size)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
func configureSpaceship() {
let middleRow = Int(Double(unwrappedMatrix.rowsCount) / 2)
let middleColumn = Int(Double(unwrappedMatrix.columnsCount) / 2)
let xOffset = CGFloat(level.startPoint.column - middleColumn)
let yOffset = CGFloat(level.startPoint.row - middleRow)
spaceship = SpaceshipSpriteNode(size: spaceshipSize)
spaceship.position = CGPoint(x: frame.midX + (spaceshipSize.width * xOffset), y: frame.midY + (spaceshipSize.height * yOffset))
spaceshipObject.addChild(spaceship)
addChild(spaceshipObject)
}
configureSpaceship method is called in didMove(to view: SKView)
The problem is that sometimes(1 per 3/4/5/6 cases) my spaceship is missing from the scene. Visibility, position, size are always the same, a count of the nodes on scene is the same too. Some images here link
According to comments, I have changed zPosition for my objects:
tile.zPosition = 0
spaceship.zPosition = 1.0
backgroundSpriteNode.zPosition = -1
And everything start working correct, thanks guys.

Swift SpriteKit Mario style rotating platform that stays horizontal

I am trying to create a mario style rotating platform that stays horizontal.
What I have done so far is create a simple class for this for testing purposes.
class PlatformRound: SKNode {
let platform: Platform
// MARK: - Init
init(barSize: CGSize, color: SKColor, pos: CGPoint) {
/// Base
let base = SKShapeNode(circleOfRadius: 6)
//base.name = Platform.Name.normal
base.fillColor = SKColor.darkGrayColor()
base.strokeColor = base.fillColor
base.position = pos
let rotatingAction = SKAction.rotateByAngle(CGFloat(-M_PI), duration: 8)
base.runAction(SKAction.repeatActionForever(rotatingAction))
/// Bar
let bar = Platform(size: barSize, color: color, pos: CGPointMake(0, 0 - (barSize.height / 2)), ofType: .Normal)
bar.zPosition = -200
/// Platform that supposed to stay horizontal
let platformSize = CGSizeMake(40, GameplayConfig.World.platformHeight)
let platformPos = CGPointMake(0, 0 - (bar.size.height / 2))
platform = Platform(size: platformSize, color: color, pos: platformPos, ofType: .Normal)
super.init()
addChild(base)
base.addChild(bar)
bar.addChild(platform)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I am creating a roundBase that I can rotate. I than create a bar that goes down from the base, that is added to the base node. Finally I create the platform that is supposed to stay horizontal at all times.
I am using another Platform subclass to create the bar and platform, but they are not relevant to this question.
How can I make the platform stay horizontal. I tried the following which didnt work.
1) In update in my gameScene I constantly update the platform position or zRotation
platformRound.platform.zRotation = ...
2) Create a zRotation property that gets set once the platform is added and than use that property to constantly update the zRotation.
3) Tried playing around with physicsJoints
Im sure there is a easy way that I am missing. I would appreciate any help.
This should work:
class GameScene: SKScene{
override func didMoveToView(view: SKView) {
backgroundColor = .blackColor()
let centerSprite = SKSpriteNode(color: .whiteColor(), size: CGSize(width: 10, height: 10))
centerSprite.zPosition = 3
let platform = SKSpriteNode(color: .orangeColor(), size: CGSize(width: 70, height: 20))
platform.zPosition = 2
platform.name = "platform"
let container = SKNode()
container.position = CGPoint(x: frame.midX, y: frame.midY)
container.addChild(centerSprite) //Just for debugging
container.addChild(platform)
let radius = 120
let chain = SKSpriteNode(color: .grayColor(), size: CGSize(width: 3, height: radius))
chain.position = CGPoint(x: 0, y: radius/2)
container.addChild(chain)
platform.position = CGPoint(x: 0, y: radius)
let rotatingAction = SKAction.rotateByAngle(CGFloat(-M_PI), duration: 8)
container.runAction(SKAction.repeatActionForever(rotatingAction), withKey: "rotating")
addChild(container)
}
override func didEvaluateActions() {
self.enumerateChildNodesWithName("//platform") { node,stop in
if let parent = node.parent{
node.zRotation = -parent.zRotation
}
}
}
}
What I did, is that I have added platform node into container node and applied rotation to that container. Later on, in didEvaluateActions I've adjusted the rotation of platform (to have a negative value of its parent's zRotation). And that's it.
Here is the result of what I am seeing:
The adjusting is needed, because otherwise the platform will end-up rotating along with its parent (notice how white, center sprite is being rotated along with container node).

Nodes spawning behind background and I can't bring them to the front

I'm using a repeat action. When the app first loads the sprites do spawn in front of the background and so you can see them. But then when you restart the game from the score scene, the nodes spawn behind the background and I can't get them to come to the front. Does anyone know how I can fix this?
override init(size: CGSize) {
super.init(size: size)
//Background
for var index = 0; index < 2; ++index {
let bg = SKSpriteNode(imageNamed: "background")
bg.position = CGPoint(x: -100, y: index * Int(bg.size.height))
bg.anchorPoint = CGPointZero
bg.name = "background"
self.addChild(bg)
}
runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(callEnemy), SKAction.waitForDuration(1.0)])))
The runAction is the code to repeat an action that doesn't seem to be working
//Player functions
foreground = SKNode()
addChild(foreground)
player = createPlayer()
foreground.addChild(player)
//Game hud
gameHud = SKNode()
addChild(gameHud)
}
func callEnemy() {
if player.physicsBody?.dynamic == true {
spawnEnemy()
}
}
func spawnEnemy() -> SKNode{
let enemy = SKSpriteNode(imageNamed: "Enemy1")
enemy.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: 690 )
addChild(enemy)
enemy.physicsBody = SKPhysicsBody(circleOfRadius: enemy.size.width / 2)
enemy.physicsBody?.dynamic = true
enemy.physicsBody?.allowsRotation = false
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.velocity = CGVector(dx: enemy.physicsBody!.velocity.dx, dy: -200.0)
enemy.physicsBody?.restitution = 1.0
enemy.physicsBody?.friction = 0.0
enemy.physicsBody?.angularDamping = 0.0
enemy.physicsBody?.linearDamping = 0.0
if enemy.position.y <= CGFloat(0) {
enemy.removeFromParent()
}
return enemy
}
In order to have the nodes be on top of the background you need to change their zPosition. If you specify:
bg.zPosition = 0
and
foreground.zPosition = 1
the foreground will now be on top of the background. The zPosition specifies the location of each node on the z-axis.

Attemped to add a SKNode which already has a parent - Swift

Ok. this code is driving me crazy. It just don't work. The only message I received is "Attemped to add a SKNode which already has a parent". Yes I know that there has been some discussions here, but none of them give the solution I need.
This is the code. I really appreciate any help.
import SpriteKit
class MyScene: SKScene {
let intervalShapeCreation:NSTimeInterval = 2.0 // Interval for creating the next Shape
let gravitationalAcceleration:CGFloat = -0.5 // The gravitational Y acceleration
let shapeSequenceAction = SKAction.sequence([
SKAction.scaleTo(1.0, duration: 0.5),
SKAction.waitForDuration(2.0),
SKAction.scaleTo(0, duration: 0.5),
SKAction.removeFromParent()
])
override init(size: CGSize) {
super.init(size: size)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
addBackground()
initializeScene()
}
// MARK: Level Building
func initializeScene() {
self.physicsWorld.gravity = CGVectorMake(0.0, gravitationalAcceleration)
runAction(SKAction.repeatActionForever(
SKAction.sequence([SKAction.runBlock(self.createShape),
SKAction.waitForDuration(intervalShapeCreation)])))
}
func addBackground() {
let backgroundAtlas = SKTextureAtlas(named: "background")
let background = SKSpriteNode(texture: backgroundAtlas.textureNamed("background"))
background.position = CGPoint(x: size.width/2, y: size.height/2)
background.anchorPoint = CGPointMake(0.5, 0.5)
background.zPosition = -1
background.name = "background"
self.addChild(background)
}
func createShape() {
let newShape = sSharedAllPossibleShapes[0]
print("\n shape creada: \(newShape.name)")
newShape.position = CGPointMake(size.width / 2, CGFloat( Int.random(fromZeroToMax: 500)))
self.addChild(newShape)
newShape.runAction(shapeSequenceAction)
}
}
createShape doesn't actually create a SKShapeNode. It gets the first shape from the sSharedAllPossibleShapes array, then adds it as child to self. The second time you call this method that shape already has a parent and can't be added again.
You have to create a new instance of SKShapeNode. The way I see it your array here really needs to contain the CGPath objects that define the shape, not the nodes themselves because you can't reuse nodes the way you intended to.