app keeps crashing , Terminating app due to uncaught exception 'NSInvalidArgumentException' - ios

I am creating a game where random objects fall in random places and there is a ball with a fixed y-axis and keeps moving along the x-axis , and it has to move throw the objects , and i am trying to count the scores and the way i do it is i created a physics object and it is places in the same y-axis as the ball , and when the objects collide the score function should be called and increment the score by 1, but for some reason the app keeps crashing and it gives me this error.
2015-07-13 01:23:17.242 WalkRun[26792:3773366] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: <SKSpriteNode> name:'(null)' texture:[<SKTexture> 'shortwall' (60 x 60)] position:{30, 768} size:{60, 60} rotation:0.00'
*** First throw call stack:
(
0 CoreFoundation 0x00000001073c33f5 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001092eabb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001073c332d +[NSException raise:format:] + 205
3 SpriteKit 0x0000000107ebfaf6 -[SKNode addChild:] + 111
4 WalkRun 0x00000001071c8c44 _TFC7WalkRun9PlayScene10leftObjectfS0_FT_T_ + 2868
5 WalkRun 0x00000001071c7ddc _TFC7WalkRun9PlayScene10randObjectfS0_FT_T_ + 236
6 WalkRun 0x00000001071c8102 _TToFC7WalkRun9PlayScene10randObjectfS0_FT_T_ + 34
7 Foundation 0x0000000107a39fd4 __NSFireTimer + 83
8 CoreFoundation 0x000000010732b4e4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
9 CoreFoundation 0x000000010732b0a5 __CFRunLoopDoTimer + 1045
10 CoreFoundation 0x00000001072ee3dd __CFRunLoopRun + 1901
11 CoreFoundation 0x00000001072eda06 CFRunLoopRunSpecific + 470
12 GraphicsServices 0x000000010e7569f0 GSEventRunModal + 161
13 UIKit 0x0000000108046550 UIApplicationMain + 1282
14 WalkRun 0x00000001071d54ce top_level_code + 78
15 WalkRun 0x00000001071d550a main + 42
16 libdyld.dylib 0x0000000109ad9145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
and this is my code:
//
// PlayScene.swift
// WalkRun
//
// Created by naeim on 7/10/15.
// Copyright (c) 2015 naeim. All rights reserved.
//
import Foundation
import SpriteKit
class PlayScene: SKScene, SKPhysicsContactDelegate{
var ball = SKSpriteNode(imageNamed: "ball")
var wall = SKNode()
var wallRight = SKNode()
var wallMiddle = SKNode()
var ballSpeed = CGFloat()
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
var ballGroup:UInt32 = 1
var objectGroup:UInt32 = 2
var gapGroup:UInt32 = 3
var gameOver = 0
var movingObjects = SKNode()
var score = 0
var scoreLabel = SKLabelNode()
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
backgroundColor = UIColor(hex: 0x80d9ff)
self.physicsWorld.gravity = CGVectorMake(-9,0)
self.addChild(movingObjects)
//creating the ball
ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame) + self.ball.size.height * 2)
ball.physicsBody = SKPhysicsBody(circleOfRadius: self.ball.size.width / 2)
ball.zPosition = 10
//let the ball rotate forever
ballSpeed = 3
let rotateAction = SKAction.rotateByAngle(ballSpeed, duration: 1)
let repeatAction = SKAction.repeatActionForever(rotateAction)
ball.runAction(repeatAction)
ball.physicsBody?.categoryBitMask = ballGroup
ball.physicsBody?.collisionBitMask = objectGroup
ball.physicsBody?.contactTestBitMask = objectGroup
self.addChild(ball)
//creating the wall of the left
wall.position = CGPointMake(CGRectGetMinX(self.frame),CGRectGetMinY(self.frame))
wall.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(2, self.frame.size.height * 2.0))
wall.physicsBody?.dynamic = false
wall.physicsBody?.categoryBitMask = objectGroup
self.addChild(wall)
//creating the wall of the right
wallRight.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMinY(self.frame))
wallRight.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(2, self.frame.size.height * 2.0))
wallRight.physicsBody?.dynamic = false
wallRight.physicsBody?.categoryBitMask = objectGroup
self.addChild(wallRight)
//creating the middle wall that objects pass by
wallMiddle.position = CGPointMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame))
wallMiddle.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 1))
wallMiddle.physicsBody?.dynamic = false
wallMiddle.physicsBody?.categoryBitMask = gapGroup
wallMiddle.physicsBody?.collisionBitMask = gapGroup
wallMiddle.physicsBody?.contactTestBitMask = objectGroup
self.addChild(wallMiddle)
//creating the label
scoreLabel.fontName = "Helvetica"
scoreLabel.fontSize = 60
scoreLabel.text = "0"
scoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) + 70 )
self.addChild(scoreLabel)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("randObject"), userInfo: nil, repeats: true)
var timerObjects = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("checkObjectPlace"), userInfo: nil, repeats: true)
}
func checkObjectPlace(){
}
//function to randomly choose which object
func randObject(){
if gameOver == 0{
var rand = arc4random_uniform(6)+1
switch(rand){
case 1:
leftObject()
case 2:
middleObject()
case 3:
rightObject()
case 4:
LeftAndMiddleObject()
case 5:
rightAndLeftObject()
case 6:
rightAndMiddleObject()
default:
println("error !! non a number other than 0, 1, 2 has been choosen .")
}
}
}
//function to create the left objects
func leftObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
bigWall.position = CGPointMake(CGRectGetMinX(self.frame) + bigWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
bigWall.runAction(moveAndRemoveObjects)
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(bigWall)
}
else
{
tallWall.position = CGPointMake(CGRectGetMinX(self.frame) + tallWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
}
}
//function to create the middle objects
func middleObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
bigWall.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
bigWall.runAction(moveAndRemoveObjects)
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(bigWall)
}
else
{
var tallWall = SKSpriteNode(imageNamed: "tallwall")
tallWall.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
}
}
//function to create the right objects
func rightObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
bigWall.position = CGPointMake(CGRectGetMaxX(self.frame) - bigWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
bigWall.runAction(moveAndRemoveObjects)
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(bigWall)
}
else
{
var tallWall = SKSpriteNode(imageNamed: "tallwall")
tallWall.position = CGPointMake(CGRectGetMaxX(self.frame) - tallWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
if ball.position.x == tallWall.position.x{
scoreIncrement()
}
}
}
//function to create a right and left object
func rightAndLeftObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
tallWall.position = CGPointMake(CGRectGetMinX(self.frame) + tallWall.size.width / 2, CGRectGetMaxY(self.frame))
bigWall.position = CGPointMake(CGRectGetMaxX(self.frame) - bigWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
bigWall.runAction(moveAndRemoveObjects)
tallWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
bigWall.position = CGPointMake(CGRectGetMaxX(self.frame) - bigWall.size.width / 2, CGRectGetMaxY(self.frame))
}
else
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
bigWall.position = CGPointMake(CGRectGetMaxX(self.frame) - bigWall.size.width / 2, CGRectGetMaxY(self.frame))
tallWall.position = CGPointMake(CGRectGetMaxX(self.frame) - tallWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
tallWall.runAction(moveAndRemoveObjects)
bigWall.runAction(moveAndRemoveObjects)
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
}
}
func rightAndMiddleObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
tallWall.position = CGPointMake(CGRectGetMaxX(self.frame) - tallWall.size.width / 2, CGRectGetMaxY(self.frame))
bigWall.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
bigWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
}
else
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
bigWall.position = CGPointMake(CGRectGetMidX(self.frame) , CGRectGetMaxY(self.frame))
tallWall.position = CGPointMake(CGRectGetMaxX(self.frame) - tallWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
bigWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
}
}
func LeftAndMiddleObject(){
var rand = arc4random_uniform(2) + 1
if rand == 1
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
tallWall.position = CGPointMake(CGRectGetMinX(self.frame) + tallWall.size.width / 2, CGRectGetMaxY(self.frame))
bigWall.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
bigWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
}
else
{
var bigWall = SKSpriteNode(imageNamed: "shortwall")
var tallWall = SKSpriteNode(imageNamed: "tallwall")
bigWall.position = CGPointMake(CGRectGetMidX(self.frame) , CGRectGetMaxY(self.frame))
tallWall.position = CGPointMake(CGRectGetMinX(self.frame) + tallWall.size.width / 2, CGRectGetMaxY(self.frame))
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
tallWall.runAction(moveAndRemoveObjects)
bigWall.runAction(moveAndRemoveObjects)
tallWall.physicsBody = SKPhysicsBody(rectangleOfSize: tallWall.size)
tallWall.physicsBody?.dynamic = false
bigWall.physicsBody = SKPhysicsBody(rectangleOfSize: bigWall.size)
bigWall.physicsBody?.dynamic = false
bigWall.physicsBody?.categoryBitMask = objectGroup
tallWall.physicsBody?.categoryBitMask = objectGroup
movingObjects.addChild(tallWall)
movingObjects.addChild(bigWall)
}
}
func scoreIncrement(){
score = score + 1
scoreLabel.text = "\(score)"
}
func didBeginContact(contact: SKPhysicsContact) {
println("contact")
if contact.bodyA.categoryBitMask == gapGroup || contact.bodyB.categoryBitMask == gapGroup {
println("gap contact")
} else {
gameOver = 1
movingObjects.speed = 0
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if gameOver == 0 {
ball.physicsBody?.velocity = CGVectorMake(0, 0)
ball.physicsBody?.applyImpulse(CGVectorMake(70,0))
}
}
override func update(currentTime: NSTimeInterval) {
}
}

The error suggests you are trying to add a child to a node while it already has a parent. The stack trace points you to leftObject method. In here you have an SKAction setup to move over a time interval and then remove from parent.
var moveObjects = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: NSTimeInterval(self.frame.size.height / 100))
var removeObjects = SKAction.removeFromParent()
var moveAndRemoveObjects = SKAction.sequence([moveObjects,removeObjects])
bigWall.runAction(moveAndRemoveObjects)
This adds the action to the node and it runs but your code path will continue down to
movingObjects.addChild(bigWall)
almost instantly. Looks like a race condition where you think the code will wait until the action has finished running before continuing on.

You have a instance property called bigWall and in most of your methods you create a local object called bigWall and add it to the scene. Since it is a new object each time the methods are call that works fine. However in the method leftObject you do not have a local object bigWall so it is referencing the instance property. The first time you call leftObject it will work fine adding your instance property bigWall to the scene. The second time you call the method it will try to add the bigWall instance property to the scene when it is already in the scene and that is where you will get the error.

Related

Sprite Kit how to apply boundaries

I am currently new for sprite kit and I am very confused my player goes all the way right outside of the frame, however I have included this part of code
let frame = SKPhysicsBody(edgeLoopFrom: self.frame)
frame.friction = 0
frame.restitution = 1
frame.categoryBitMask = bitMask.frame.rawValue
frame.contactTestBitMask = bitMask.player.rawValue
frame.collisionBitMask = bitMask.player.rawValue
self.physicsBody = frame
The full code is bellow
class GameScene : SKScene, SKPhysicsContactDelegate {
let background = SKSpriteNode(imageNamed: "bg")
let player = SKSpriteNode(imageNamed: "PlayerJump")
let ground = SKSpriteNode(imageNamed: "ground")
let gameOverLine = SKSpriteNode(color: .red, size: CGSize(width: 900, height: 10))
let rightBorderLine = SKSpriteNode(color: .red, size: CGSize(width: 10, height: 900))
let scoreLabel = SKLabelNode()
let bestScoreLabel = SKLabelNode()
let defaults = UserDefaults.standard
let cam = SKCameraNode()
let motionManager = CMMotionManager()
var firstTouch = false
var score = 0
var bestScore = 0
var multi: CGFloat = 0.0
enum bitMask: UInt32 {
case player = 0b1
case platform = 0b10
case gameOverLine
case frame
}
override func didMove(to view: SKView) {
self.size = CGSize(width: UIScreen.main.bounds.width * 2, height: UIScreen.main.bounds.height * 2)
self.anchorPoint = .zero
background.position = CGPoint(x: size.width / 2, y: size.height / 2)
background.zPosition = 1
addChild(background)
physicsWorld.contactDelegate = self
ground.position = CGPoint(x: size.width / 2, y: 10)
ground.zPosition = 5
ground.setScale(2.5)
ground.physicsBody = SKPhysicsBody(rectangleOf: ground.size)
ground.physicsBody?.isDynamic = false
ground.physicsBody?.allowsRotation = false
ground.physicsBody?.affectedByGravity = false
addChild(ground)
player.position = CGPoint(x: size.width / 2, y: size.height/8)
player.zPosition = 10
player.setScale(1.8)
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.height / 2)
player.physicsBody?.isDynamic = false
player.physicsBody?.restitution = 1
player.physicsBody?.friction = 0
player.physicsBody?.angularDamping = 1
player.physicsBody?.categoryBitMask = bitMask.player.rawValue
player.physicsBody?.collisionBitMask = 0
player.physicsBody?.contactTestBitMask = bitMask.platform.rawValue | bitMask.gameOverLine.rawValue
// player.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
addChild(player)
gameOverLine.position = CGPoint(x: player.position.x, y: player.position.y - 240)
gameOverLine.zPosition = -1
gameOverLine.physicsBody = SKPhysicsBody(rectangleOf: gameOverLine.size)
gameOverLine.physicsBody?.affectedByGravity = false
gameOverLine.physicsBody?.allowsRotation = false
gameOverLine.physicsBody?.categoryBitMask = bitMask.gameOverLine.rawValue
gameOverLine.physicsBody?.contactTestBitMask = bitMask.platform.rawValue | bitMask.player.rawValue
addChild(gameOverLine)
scoreLabel.position.x = 125
scoreLabel.zPosition = 20
scoreLabel.fontColor = .black
scoreLabel.fontSize = 32
scoreLabel.fontName = "Helvectica"
scoreLabel.text = "Score: \(score)"
addChild(scoreLabel)
bestScore = defaults.integer(forKey: "best")
bestScoreLabel.position.x = 625
bestScoreLabel.zPosition = 20
bestScoreLabel.fontColor = .black
bestScoreLabel.fontSize = 32
bestScoreLabel.fontName = "Helvectica"
bestScoreLabel.text = "Bestscore: \(bestScore)"
addChild(bestScoreLabel)
makePlatform()
makePlatform2()
makePlatform3()
makePlatform4()
makePlatform5()
makePlatform6()
// if motionManager.isAccelerometerActive == true {
// motionManager.accelerometerUpdateInterval = 20/60
//
// motionManager.startAccelerometerUpdates(to: OperationQueue()) { data, error in
//
// self.multi = Float(data!.acceleration.x) * 10
// self.player.position = CGPoint(x: self.player.position.x + CGFloat(self.multi), y: self.player.position.y)
// }
// }
if motionManager.isAccelerometerAvailable {
motionManager.accelerometerUpdateInterval = 0.10
motionManager.startAccelerometerUpdates(to: .main) {
(data, error) in
guard let data = data, error == nil else {
return
}
let currentX = self.player.position.x
self.multi = currentX + CGFloat(data.acceleration.x * 1300)
}
}
let frame = SKPhysicsBody(edgeLoopFrom: self.frame)
frame.friction = 0
frame.restitution = 1
frame.categoryBitMask = bitMask.frame.rawValue
frame.contactTestBitMask = bitMask.player.rawValue
frame.collisionBitMask = bitMask.player.rawValue
self.physicsBody = frame
cam.setScale(3)
cam.position.x = player.position.x
camera = cam
}
override func update(_ currentTime: TimeInterval) {
cam.position.y = player.position.y + 350
background.position.y = player.position.y
if player.physicsBody!.velocity.dy > 0 {
gameOverLine.position.y = player.position.y - 600
}
scoreLabel.position.y = player.position.y + 1050
bestScoreLabel.position.y = player.position.y + 1050
let action = SKAction.moveTo(x: multi, duration: 1)
player.run(action)
}
func didBegin(_ contact: SKPhysicsContact) {
let contactA: SKPhysicsBody
let contactB: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
contactA = contact.bodyA //Player
contactB = contact.bodyB //Platform
} else {
contactA = contact.bodyB //Player
contactB = contact.bodyA //Platform
}
if contactA.categoryBitMask == bitMask.platform.rawValue && contactB.categoryBitMask == bitMask.gameOverLine.rawValue {
contactA.node?.removeFromParent()
}
if contactA.categoryBitMask == bitMask.player.rawValue && contactB.categoryBitMask == bitMask.platform.rawValue {
if player.physicsBody!.velocity.dy < 0 {
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 1400)
contactB.node?.removeFromParent()
makePlatform5()
makePlatform6()
addScore()
}
}
if contactA.categoryBitMask == bitMask.player.rawValue && contactB.categoryBitMask == bitMask.gameOverLine.rawValue {
gameOver()
}
}
// override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// for touch in touches {
// let location = touch.location(in: self)
//
// player.position.x = location.x
// }
// }
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
player.physicsBody?.isDynamic = true
if firstTouch == false {
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 1800))
}
firstTouch = true
}
func makePlatform() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 140, highestValue: 300).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func makePlatform2() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 350, highestValue: 550).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func makePlatform3() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 600, highestValue: 800).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func makePlatform4() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 850, highestValue: 1050).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func makePlatform5() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 1100, highestValue: 1300).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func makePlatform6() {
let platform = SKSpriteNode(imageNamed: "ground")
platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 70, highestValue: 700).nextInt(), y: GKRandomDistribution(lowestValue: 1350, highestValue: 1550).nextInt() + Int(player.position.y))
platform.zPosition = 5
platform.setScale(0.30)
platform.physicsBody = SKPhysicsBody(rectangleOf: platform.size)
platform.physicsBody?.isDynamic = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.categoryBitMask = bitMask.platform.rawValue
platform.physicsBody?.collisionBitMask = 0
platform.physicsBody?.contactTestBitMask = bitMask.player.rawValue
addChild(platform)
}
func gameOver() {
let gameOverScene = GameOverScene(size: self.size)
let transition = SKTransition.crossFade(withDuration: 0.5)
view?.presentScene(gameOverScene, transition: transition)
if score > bestScore {
bestScore = score
defaults.set(bestScore, forKey: "best")
}
}
func addScore() {
score += 1
scoreLabel.text = "Score: \(score)"
}
}

The enemy's healthbar decreases in its entirety with a single collision

he problem is that when the player collides with the enemy the health of the enemy in healthBar does not decrease the indicated amount. it simply decreases in its entirety
I can not find a way to update the enemy's healthbar in the func update and try the func didBegin (_ contact: SKPhysicsContact)
enter code here
func initZombie(){
let enemy = Enemigo(imageNamed: "zombie1")
var textures:[SKTexture] = []
for i in 1...2 {
textures.append(SKTexture(imageNamed: "zombie\(i)"))
}
let anima:SKAction = SKAction.animate(with: textures, timePerFrame: 15.0)
enemy.run(SKAction.group([
SKAction.repeatForever(anima),
SKAction.speed(to: 60.0, duration: 0)
]),withKey: "animation")
enemy.healt = 300
enemy.exp = 100
enemy.barraEnemy = SKSpriteNode(color: SKColor.green, size: enemy.barravidaSizeE)
enemy.barraEnemyBack = SKSpriteNode(color: SKColor.red, size: CGSize(width: enemy.barravidaSizeE.width + 300, height: enemy.barravidaSizeE.height + 30))
enemy.barraEnemy.position = CGPoint(x: enemy.position.x , y: enemy.position.y - 150)
enemy.barraEnemy.zPosition = 101
enemy.barraEnemy.anchorPoint = CGPoint(x: 0.0 , y: 0.5)
enemy.addChild(enemy.barraEnemy)
enemy.barraEnemyBack.position = CGPoint(x: enemy.position.x , y: enemy.position.y - 150)
enemy.barraEnemyBack.zPosition = 100
enemy.barraEnemyBack.anchorPoint = CGPoint(x: 0.0, y: 0.5)
enemy.addChild(enemy.barraEnemyBack)
enemy.barraEnemy.size = CGSize(width: enemy.barravidaSizeE.width + CGFloat(enemy.healt) , height: enemy.barravidaSizeE.height + 30)
enemy.zPosition = 100
//enemy.position = CGPoint(x: size.width/2, y: size.height/2)
enemy.position = CGPoint(x:random(min: -1100 , max: 1100), y: random(min: -400 , max: 400))
enemy.name = "zombie"
enemy.setScale(0.4)
addChild(enemy)
enemy.physicsBody = SKPhysicsBody.init(rectangleOf: enemy.size)
enemy.physicsBody?.allowsRotation = true
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = 3
enemy.physicsBody?.collisionBitMask = 1
enemy.physicsBody?.contactTestBitMask = 1
enemy.physicsBody?.isDynamic = true
}
enter
code
here
func didBegin(_ contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
}else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == 1 && secondBody.categoryBitMask == 2 {
life += 100
secondBody.node?.removeFromParent()
}
if firstBody.categoryBitMask == 1 && secondBody.categoryBitMask == 3 {
score += 1
if let myEnemy = secondBody.node as? Enemigo {
myEnemy.healt -= playerAtack
life -= zombieAtack
myEnemy.barraEnemy.size = CGSize(width: myEnemy.barravidaSizeE.width + CGFloat(myEnemy.healt), height: myEnemy.barravidaSizeE.height)
print(myEnemy.healt)
if myEnemy.healt <= 0 {
playerAtack += 10
life += 100
spawnItem(point: secondBody.node!.position)
secondBody.node?.removeFromParent()
}
}
}
}

In Sprite Kit, when I am spawning nodes, why do they all appear on the top right of the screen?

MainPlayer is the main ball in the center, and I want the blue enemy nodes to spawn randomly on each side, but they are all appearing in the top right. I am pretty sure this code is correct, and I cannot get it to work. It seems like they are spawning in the right place, but it is just scaled to the top right for some reason.
func Enemies() {
let xPos = randomBetweenNumbers(firstNum: 0, secondNum: frame.width )
let Enemy = SKSpriteNode(imageNamed: "Ball")
Enemy.zPosition = -1.0
Enemy.size = CGSize(width: 20.0, height: 20.0)
Enemy.physicsBody?.categoryBitMask = PhysicsCategory.Enemy
Enemy.physicsBody?.contactTestBitMask = PhysicsCategory.Smallball | PhysicsCategory.MainBall
Enemy.physicsBody?.collisionBitMask = PhysicsCategory.Smallball | PhysicsCategory.MainBall
let randomNumber = arc4random() % 4 + 1
switch randomNumber {
case 0:
Enemy.position.x = 0
var positionY = arc4random_uniform(UInt32(frame.size.height))
Enemy.position.y = CGFloat(positionY)
self.addChild(Enemy)
break
case 1:
Enemy.position.y = 0
var positionX = arc4random_uniform(UInt32(frame.size.width))
Enemy.position.x = CGFloat(positionX)
self.addChild(Enemy)
break
case 2:
Enemy.position.y = frame.size.height
var positionX = arc4random_uniform(UInt32(frame.size.width))
Enemy.position.x = CGFloat(positionX)
self.addChild(Enemy)
break
case 3:
Enemy.position.x = frame.size.width
var positionY = arc4random_uniform(UInt32(frame.size.height))
Enemy.position.y = CGFloat(positionY)
self.addChild(Enemy)
break
default:
break
}
Enemy.position = CGPoint(x: CGFloat(xPos), y: self.frame.size.height / 2)
Enemy.physicsBody = SKPhysicsBody(circleOfRadius: 7)
Enemy.physicsBody?.affectedByGravity = false
Enemy.physicsBody?.categoryBitMask = 0
Enemy.physicsBody?.contactTestBitMask = 1
addChild(Enemy)
Enemy.run(SKAction.move(to: MainPlayer.position, duration: 3))
}
This is the result of my code, and obviously, I just let it spawn instead of move to the ball because I wanted to show the weird spawning locations.
try this:
let Enemy = SKSpriteNode(imageNamed: "Ball")
Enemy.zPosition = -1.0
Enemy.size = CGSize(width: 20.0, height: 20.0)
Enemy.physicsBody?.categoryBitMask = PhysicsCategory.Enemy
Enemy.physicsBody?.contactTestBitMask = PhysicsCategory.Smallball | PhysicsCategory.MainBall
Enemy.physicsBody?.collisionBitMask = PhysicsCategory.Smallball | PhysicsCategory.MainBall
Enemy.physicsBody?.affectedByGravity = false
Enemy.physicsBody?.isDynamic = true
Remove the code after break except Enemy.run(SKAction.move(to: MainPlayer.position, duration: 3))
Also, try removing the +1 after arc4random

flappy bird clone Xcode 7 Swift 2 how to reset rotation

I learn how to create games on iOS. And now I create a Flappy bird clone.
Flappy Bird Clone
And I'm stack on that - when bird touch some pipe it begin rotate. And game of course is over. But when I start a new game Bird still rotates.
If I put this line
bird.physicsBody?.allowsRotation = false
in the GameScene.swift then bird stop rotate at all. That is not what I want. I want to allow rotation. But when start a new game Bird should be in default position and do not rotate.
What should I do to make it work? Thanks for help.
//
// GameScene.swift
// Flappy Bird
//
// Created by Admin on 10.10.15.
// Copyright (c) 2015 Alex. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var score = 0
var gameOver = false
var gameOverLabel = SKLabelNode()
var scoreLabel = SKLabelNode ()
var bird = SKSpriteNode()
var bg = SKSpriteNode()
var movingObjects = SKSpriteNode()
var labelContainer = SKSpriteNode()
var pipe1 = SKSpriteNode()
var pipe2 = SKSpriteNode()
enum ColliderType: UInt32 {
case Bird = 1
case Object = 2
case Gap = 4
}
func makeBg () {
let bgTexture = SKTexture(imageNamed: "bg.png")
let movebg = SKAction.moveByX(-bgTexture.size().width, y: 0, duration: 10)
let replacebg = SKAction.moveByX(bgTexture.size().width, y: 0, duration: 0)
let movebgForever = SKAction.repeatActionForever(SKAction.sequence([movebg,replacebg]))
for var i: CGFloat = 0; i<2; i++ {
bg = SKSpriteNode(texture: bgTexture)
bg.position = CGPoint(x: bgTexture.size().width / 2 + bgTexture.size().width * i, y: CGRectGetMidY(self.frame))
bg.zPosition = -5
bg.size.height = self.frame.height
bg.runAction(movebgForever)
movingObjects.addChild(bg)
}
}
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
self.addChild(movingObjects)
self.addChild(labelContainer)
makeBg()
scoreLabel.fontName = "Helvetica"
scoreLabel.fontSize = 60
scoreLabel.text = "0"
scoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.size.height - 70)
addChild(scoreLabel)
let birdTexture = SKTexture(imageNamed: "flappy1.png")
let birdTexture2 = SKTexture(imageNamed: "flappy2.png")
let animation = SKAction.animateWithTextures([birdTexture,birdTexture2], timePerFrame: 0.1)
let makeBirdFlap = SKAction.repeatActionForever(animation)
bird = SKSpriteNode(texture: birdTexture)
bird.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
bird.runAction(makeBirdFlap)
bird.physicsBody = SKPhysicsBody(circleOfRadius: birdTexture.size().height/2)
bird.physicsBody!.dynamic = true
bird.physicsBody!.categoryBitMask = ColliderType.Bird.rawValue
bird.physicsBody?.contactTestBitMask = ColliderType.Object.rawValue
bird.physicsBody?.collisionBitMask = ColliderType.Object.rawValue
self.addChild(bird)
var ground = SKNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.size.width, 1))
ground.physicsBody!.dynamic = false
ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody?.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody?.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)
_ = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: Selector("makePipes"), userInfo: nil, repeats: true)
}
func makePipes () {
let gapHeight = bird.size.height * 4
let movementAmount = arc4random() % UInt32(self.frame.size.height / 2)
let pipeOffset = CGFloat(movementAmount) - self.frame.size.height / 4
let movePipes = SKAction.moveByX(-self.frame.size.width * 2, y: 0, duration: NSTimeInterval (self.frame.size.width / 100))
let removePipes = SKAction.removeFromParent()
let moveAndRemovePipes = SKAction.sequence([movePipes,removePipes])
let pipeTexture1 = SKTexture(imageNamed: "pipe1.png")
let pipe1 = SKSpriteNode(texture: pipeTexture1)
pipe1.position = CGPoint(x: CGRectGetMidX(self.frame) + self.frame.size.width, y: CGRectGetMidY(self.frame) + pipeTexture1.size().height/2 + gapHeight/2 + pipeOffset)
pipe1.runAction(moveAndRemovePipes)
pipe1.physicsBody = SKPhysicsBody(rectangleOfSize: pipeTexture1.size())
pipe1.physicsBody?.dynamic = false
pipe1.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
pipe1.physicsBody?.contactTestBitMask = ColliderType.Object.rawValue
pipe1.physicsBody?.collisionBitMask = ColliderType.Object.rawValue
movingObjects.addChild(pipe1)
let pipeTexture2 = SKTexture(imageNamed: "pipe2.png")
let pipe2 = SKSpriteNode(texture: pipeTexture2)
pipe2.position = CGPoint(x: CGRectGetMidX(self.frame) + self.frame.size.width, y: CGRectGetMidY(self.frame) - pipeTexture2.size().height/2 - gapHeight/2 + pipeOffset)
pipe2.runAction(moveAndRemovePipes)
pipe2.physicsBody = SKPhysicsBody(rectangleOfSize: pipeTexture2.size())
pipe2.physicsBody!.dynamic = false
pipe2.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
pipe2.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
pipe2.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
movingObjects.addChild(pipe2)
var gap = SKNode()
gap.position = CGPoint(x: CGRectGetMidX(self.frame) + self.frame.size.width, y: CGRectGetMidY(self.frame) + pipeOffset)
gap.runAction(moveAndRemovePipes)
gap.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(pipe1.size.width, gapHeight))
gap.physicsBody?.dynamic = false
gap.physicsBody!.categoryBitMask = ColliderType.Gap.rawValue
gap.physicsBody!.contactTestBitMask = ColliderType.Bird.rawValue
gap.physicsBody!.collisionBitMask = ColliderType.Gap.rawValue
movingObjects.addChild(gap)
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == ColliderType.Gap.rawValue || contact.bodyB.categoryBitMask == ColliderType.Gap.rawValue {
score++
scoreLabel.text = String(score)
} else {
if gameOver == false {
gameOver = true
self.speed = 0
gameOverLabel.fontName = "Helvetica"
gameOverLabel.fontSize = 30
gameOverLabel.text = "Game is over. Tap to play again."
gameOverLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
labelContainer.addChild(gameOverLabel)
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if gameOver == false {
bird.physicsBody!.velocity = CGVectorMake(0, 0)
bird.physicsBody!.applyImpulse(CGVectorMake(0, 50))
} else {
score = 0
scoreLabel.text = "0"
bird.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bird.physicsBody?.velocity = CGVectorMake(0, 0)
bird.physicsBody!.allowsRotation = false
movingObjects.removeAllChildren()
makeBg()
self.speed = 1
gameOver = false
labelContainer.removeAllChildren()
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
An easy solution is to reset the bird's angular speed and rotation angle. Modify the code in touchesBegan which is invoked when game is over:
bird.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bird.physicsBody?.velocity = CGVectorMake(0, 0)
bird.physicsBody?.angularVelocity = 0
bird.zRotation = 0

iOS Simulator doesn't show the correct scene until after two touches

I'm creating a game with a main menu, but when I run the game in iOS Simulator it doesn't show the scene correctly, like shown in the screenshot below.
However, when I move to the option menu scene and return to the main menu scene it shows the scene in the correct way.
This is the code for the main menu:
let playButton = SKSpriteNode(imageNamed: "PlayButton")
let optionButton = SKSpriteNode(imageNamed: "Options")
let facebookButton = SKSpriteNode(imageNamed: "Facebook")
let twitterButton = SKSpriteNode(imageNamed: "Twitter")
let gamecenterButton = SKSpriteNode(imageNamed: "Gamecenter")
let nosoundButton = SKSpriteNode(imageNamed: "Nosound")
let runningBar = SKSpriteNode(imageNamed: "Bar")
let character = SKSpriteNode(imageNamed: "Character")
let backgroundImage = SKSpriteNode(imageNamed: "Background")
let mountains = SKSpriteNode(imageNamed: "Mountains")
let water = SKSpriteNode(imageNamed: "Water")
let sand = SKSpriteNode(imageNamed: "Sand")
let sun = SKSpriteNode(imageNamed: "Sun")
let cloud01 = SKSpriteNode(imageNamed: "Cloud01")
let cloud02 = SKSpriteNode(imageNamed: "Cloud02")
let cloud03 = SKSpriteNode(imageNamed: "Cloud03")
override func didMoveToView(view: SKView) {
addScene()
addMenuButtons()
addSocial()
}
func addScene() {
self.backgroundImage.anchorPoint = CGPointMake(0.5, 0.5)
self.backgroundImage.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.backgroundImage.size.width = self.frame.size.width * 1.4
self.backgroundImage.size.height = self.frame.size.height * 1.4
self.backgroundImage.zPosition = 1
self.mountains.anchorPoint = CGPointMake(0.5, 0.5)
self.mountains.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.mountains.size.width = self.frame.size.width * 1.4
self.mountains.size.height = self.frame.size.height * 1.4
self.mountains.zPosition = 2
self.water.anchorPoint = CGPointMake(0.5, 0.5)
self.water.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.water.size.width = self.frame.size.width * 1.4
self.water.size.height = self.frame.size.height * 1.4
self.water.zPosition = 3
self.sand.anchorPoint = CGPointMake(0, 0)
self.sand.position = CGPointMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame))
self.sand.size.width = self.frame.size.width
self.sand.size.height = self.frame.size.height
self.sand.zPosition = 4
self.sun.anchorPoint = CGPointMake(0.5, 0.5)
self.sun.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMaxY(self.frame))
self.sun.size.width = 150
self.sun.size.height = 150
self.sun.zPosition = 2
self.cloud01.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud01.size.width = self.frame.size.width / 3
self.cloud01.size.height = self.cloud01.size.width / 5
self.cloud01.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) - 50)
self.cloud01.zPosition = 2
self.cloud02.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud02.size.width = self.frame.size.width / 3
self.cloud02.size.height = self.cloud01.size.width / 5
self.cloud02.position = CGPointMake(CGRectGetMaxX(self.frame) - 50, CGRectGetMaxY(self.frame) - 200)
self.cloud02.zPosition = 2
self.cloud03.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud03.size.width = self.frame.size.width / 3
self.cloud03.size.height = self.cloud01.size.width / 5
self.cloud03.position = CGPointMake(CGRectGetMinX(self.frame) + 50, CGRectGetMaxY(self.frame) - 125)
self.cloud03.zPosition = 2
self.addChild(self.backgroundImage)
self.addChild(self.mountains)
self.addChild(self.water)
self.addChild(self.sand)
self.addChild(self.sun)
self.addChild(self.cloud01)
self.addChild(self.cloud02)
self.addChild(self.cloud03)
}
func addMenuButtons() {
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) * (3/5))
self.playButton.size.width = self.frame.size.width * (36/100)
self.playButton.size.height = self.playButton.size.width * (18/100)
self.playButton.zPosition = 5
self.optionButton.position = CGPointMake(CGRectGetMidX(self.frame), self.playButton.position.y - self.playButton.size.height - 10)
self.optionButton.size.width = self.frame.size.width * (36/100)
self.optionButton.size.height = self.optionButton.size.width * (18/100)
self.optionButton.zPosition = 5
self.nosoundButton.anchorPoint = CGPointMake(1, 0)
self.nosoundButton.position = CGPointMake(CGRectGetMaxX(self.frame) - 10, CGRectGetMinY(self.frame) + 10)
self.nosoundButton.size.height = 40
self.nosoundButton.size.width = 40
self.nosoundButton.zPosition = 5
// Add buttons
self.addChild(self.playButton)
self.addChild(self.optionButton)
self.addChild(self.nosoundButton)
}
func addSocial() {
self.twitterButton.anchorPoint = CGPointMake(0, 0)
self.twitterButton.position = CGPointMake(CGRectGetMinX(self.frame) + 10, CGRectGetMinY(self.frame) + 10)
self.twitterButton.size.height = 40
self.twitterButton.size.width = 40
self.twitterButton.zPosition = 5
self.facebookButton.anchorPoint = CGPointMake(0, 0)
self.facebookButton.position = CGPointMake(CGRectGetMinX(self.frame) + 10, self.twitterButton.position.y + self.twitterButton.size.height + 5)
self.facebookButton.size.height = 40
self.facebookButton.size.width = 40
self.facebookButton.zPosition = 5
self.gamecenterButton.anchorPoint = CGPointMake(1, 0)
self.gamecenterButton.position = CGPointMake(CGRectGetMaxX(self.frame) - 10, self.nosoundButton.position.y + self.nosoundButton.size.height + 5)
self.gamecenterButton.size.height = 40
self.gamecenterButton.size.width = 40
self.gamecenterButton.zPosition = 5
self.addChild(self.twitterButton)
self.addChild(self.facebookButton)
self.addChild(self.gamecenterButton)
}
This is the option menu code:
let removeAdsButton = SKSpriteNode(imageNamed: "Removeads")
let resetHighScoreButton = SKSpriteNode(imageNamed: "Resethighscore")
let creditsButton = SKSpriteNode(imageNamed: "Credits")
let backButton = SKSpriteNode(imageNamed: "BackButton")
let facebookButton = SKSpriteNode(imageNamed: "Facebook")
let twitterButton = SKSpriteNode(imageNamed: "Twitter")
let gamecenterButton = SKSpriteNode(imageNamed: "Gamecenter")
let nosoundButton = SKSpriteNode(imageNamed: "Nosound")
let runningBar = SKSpriteNode(imageNamed: "Bar")
let backgroundImage = SKSpriteNode(imageNamed: "Background")
let mountains = SKSpriteNode(imageNamed: "Mountains")
let water = SKSpriteNode(imageNamed: "Water")
let sand = SKSpriteNode(imageNamed: "Sand")
let sun = SKSpriteNode(imageNamed: "Sun")
let cloud01 = SKSpriteNode(imageNamed: "Cloud01")
let cloud02 = SKSpriteNode(imageNamed: "Cloud02")
let cloud03 = SKSpriteNode(imageNamed: "Cloud03")
var score = 0
override func didMoveToView(view: SKView) {
addScene()
addMenuButtons()
addSocial()
}
func addScene() {
self.backgroundImage.anchorPoint = CGPointMake(0.5, 0.5)
self.backgroundImage.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.backgroundImage.size.width = self.frame.size.width * 1.4
self.backgroundImage.size.height = self.frame.size.height * 1.4
self.backgroundImage.zPosition = 1
self.mountains.anchorPoint = CGPointMake(0.5, 0.5)
self.mountains.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.mountains.size.width = self.frame.size.width * 1.4
self.mountains.size.height = self.frame.size.height * 1.4
self.mountains.zPosition = 2
self.water.anchorPoint = CGPointMake(0.5, 0.5)
self.water.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.water.size.width = self.frame.size.width * 1.4
self.water.size.height = self.frame.size.height * 1.4
self.water.zPosition = 3
self.sand.anchorPoint = CGPointMake(0, 0)
self.sand.position = CGPointMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame))
self.sand.size.width = self.frame.size.width
self.sand.size.height = self.frame.size.height
self.sand.zPosition = 4
self.sun.anchorPoint = CGPointMake(0.5, 0.5)
self.sun.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMaxY(self.frame))
self.sun.size.width = 150
self.sun.size.height = 150
self.sun.zPosition = 2
self.cloud01.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud01.size.width = self.frame.size.width / 3
self.cloud01.size.height = self.cloud01.size.width / 5
self.cloud01.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) - 50)
self.cloud01.zPosition = 2
self.cloud02.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud02.size.width = self.frame.size.width / 3
self.cloud02.size.height = self.cloud01.size.width / 5
self.cloud02.position = CGPointMake(CGRectGetMaxX(self.frame) - 50, CGRectGetMaxY(self.frame) - 200)
self.cloud02.zPosition = 2
self.cloud03.anchorPoint = CGPointMake(0.5, 0.5)
self.cloud03.size.width = self.frame.size.width / 3
self.cloud03.size.height = self.cloud01.size.width / 5
self.cloud03.position = CGPointMake(CGRectGetMinX(self.frame) + 50, CGRectGetMaxY(self.frame) - 125)
self.cloud03.zPosition = 2
self.addChild(self.backgroundImage)
self.addChild(self.mountains)
self.addChild(self.water)
self.addChild(self.sand)
self.addChild(self.sun)
self.addChild(self.cloud01)
self.addChild(self.cloud02)
self.addChild(self.cloud03)
}
func addMenuButtons() {
self.removeAdsButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) - self.removeAdsButton.size.height * (2/3))
self.removeAdsButton.size.width = self.frame.size.width * (36/100)
self.removeAdsButton.size.height = self.removeAdsButton.size.width * (18/100)
self.removeAdsButton.zPosition = 5
self.resetHighScoreButton.position = CGPointMake(CGRectGetMidX(self.frame), self.removeAdsButton.position.y - self.removeAdsButton.size.height - 5)
self.resetHighScoreButton.size.width = self.frame.size.width * (36/100)
self.resetHighScoreButton.size.height = self.resetHighScoreButton.size.width * (18/100)
self.resetHighScoreButton.zPosition = 5
self.creditsButton.position = CGPointMake(CGRectGetMidX(self.frame), self.resetHighScoreButton.position.y - self.resetHighScoreButton.size.height - 5)
self.creditsButton.size.width = self.frame.size.width * (36/100)
self.creditsButton.size.height = self.creditsButton.size.width * (18/100)
self.creditsButton.zPosition = 5
self.backButton.position = CGPointMake(CGRectGetMidX(self.frame), self.creditsButton.position.y - self.creditsButton.size.height - 5)
self.backButton.size.width = self.frame.size.width * (36/100)
self.backButton.size.height = self.backButton.size.width * (18/100)
self.backButton.zPosition = 5
self.nosoundButton.anchorPoint = CGPointMake(1, 0)
self.nosoundButton.position = CGPointMake(CGRectGetMaxX(self.frame) - 10, CGRectGetMinY(self.frame) + 10)
self.nosoundButton.size.height = 40
self.nosoundButton.size.width = 40
self.nosoundButton.zPosition = 5
// Add buttons
self.addChild(self.removeAdsButton)
self.addChild(self.resetHighScoreButton)
self.addChild(self.creditsButton)
self.addChild(self.backButton)
self.addChild(self.nosoundButton)
}
func addSocial() {
self.twitterButton.anchorPoint = CGPointMake(0, 0)
self.twitterButton.position = CGPointMake(CGRectGetMinX(self.frame) + 10, CGRectGetMinY(self.frame) + 10)
self.twitterButton.size.height = 40
self.twitterButton.size.width = 40
self.twitterButton.zPosition = 5
self.facebookButton.anchorPoint = CGPointMake(0, 0)
self.facebookButton.position = CGPointMake(CGRectGetMinX(self.frame) + 10, self.twitterButton.position.y + self.twitterButton.size.height + 5)
self.facebookButton.size.height = 40
self.facebookButton.size.width = 40
self.facebookButton.zPosition = 5
self.gamecenterButton.anchorPoint = CGPointMake(1, 0)
self.gamecenterButton.position = CGPointMake(CGRectGetMaxX(self.frame) - 10, self.nosoundButton.position.y + self.nosoundButton.size.height + 5)
self.gamecenterButton.size.height = 40
self.gamecenterButton.size.width = 40
self.gamecenterButton.zPosition = 5
self.addChild(self.twitterButton)
self.addChild(self.facebookButton)
self.addChild(self.gamecenterButton)
}
Try to replace CGRectGetMinX(self.frame) with 0 and CGRectGetMaxX(self.frame) with self.frame.size.width same for the y positions.
Solution:
I've added scene.size = skView.bounds.size to the view. This fixed the issue.

Resources