Pause and Resume SKScene - swift

I was testing my game on my iPhone and I realized that I have a problem with the home button. When I pause the game and load another app the game is not paused and continues when the app is not on screen.
Here's the code:
class GameScene: SKScene, SKPhysicsContactDelegate{
var PauseButton = SKSpriteNode(imageNamed: "pause")
var Resume = SKSpriteNode(imageNamed: "resume1")
}
init(size: CGSize, won: Bool) {
super.init(size: size)
//pause
PauseButton.position = CGPointMake(330, 700)
PauseButton.zPosition = 3;
PauseButton.size = CGSizeMake(40, 40);
PauseButton.name = "PauseButton"
self.addChild(PauseButton)
//resume
Resume = SKSpriteNode(imageNamed: "resume1")
Resume.position = CGPointMake(520, 450)
Resume.zPosition = 100
Resume.setScale(1.3)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
show = self.scene as SKScene!
for touch in touches {
let Location:CGPoint = touch.locationInNode(self)
let Node:SKNode = self.nodeAtPoint(Location)
if(Node == PauseButton){
self.show.paused = true
PauseButton.removeFromParent()
self.addChild(Resume)
}
if(Node == Resume){
Resume.removeFromParent()
self.show.paused = false
self.addChild(PauseButton)
}
How do I get the game to pause when I press the home button?

Pause the view not the scene.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let view = view else {
return
}
view.paused = !view.paused
}

SpriteKit will auto Resume when you comeback to your app. so you need :
Step 1 : create a variable :
var wasPaused : Bool = false
Step 2 : change it in your pause/resume function :
wasPaused = true // pause func
wasPaused = false // resume fun
Step 3 : in update fun of your scene:
override func update(currentTime: CFTimeInterval) {
if isPausing{
self.paused = true
return
}
}

Related

Why this function stop working as soon as I add hit boxes?

I'm trying to crate a car game where you move the car from left to right by touching the screen but as soon as I set "physics definition -> body type" and the car reach the far left or the far right of the screen, this movement function stop working.
I'm using
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let touchLocation = touch.location(in: self)
if touchLocation.x > centrePoint {
if playerCar.position.x == playerCarAtMaxLeft {
playerCar.position.x = playerCarAtLeft
playerCarMoveRight = true
playerCarMoveLeft = false
} else if playerCar.position.x == playerCarAtLeft {
playerCar.position.x = playerCarAtRight
playerCarMoveRight = true
playerCarMoveLeft = false
} else if playerCar.position.x == playerCarAtRight {
playerCar.position.x = playerCarAtMaxRight
playerCarMoveRight = true
playerCarMoveLeft = false
} else {
playerCarMoveRight = false
playerCarMoveLeft = true
}
} else {
if playerCar.position.x == playerCarAtMaxRight {
playerCar.position.x = playerCarAtRight
playerCarMoveRight = false
playerCarMoveLeft = true
} else if playerCar.position.x == playerCarAtRight {
playerCar.position.x = playerCarAtLeft
playerCarMoveRight = false
playerCarMoveLeft = true
} else if playerCar.position.x == playerCarAtLeft {
playerCar.position.x = playerCarAtMaxLeft
playerCarMoveRight = false
playerCarMoveLeft = true
} else{
playerCarMoveRight = true
playerCarMoveLeft = false
}
}
canMove = true
}
}
playerCar is a SKSpriteNode
playerCarAt... are CGFloat
playerCarMove... are Boolean
I'd suggest you just let the car slide on the x-axis as much as it wants and then use the update method to keep track of the cars position.
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
In that way you can set up let maxXPosition and as soon as the car-node hits that point, you stop the movement.
A way of doing so is to make the car-node movement an SKAction.moveTo.
A simple version would be:
class GameScene: SKScene {
var car : SKSpriteNode! // Your car sprite
var maxXPosition : CGFloat! // The max point on the x-axis the car is allowed to move to
override func didMove(to view: SKView) {
// Initiate car
car = self.childNode(withName: "//car") as? SKSpriteNode
// Setup the max x position
maxXPosition = 200
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
moveCar(toPosition: location)
}
}
override func update(_ currentTime: TimeInterval) {
// Check the cars position
if car.position.x >= 200 {
// Stop the car is the point has been reached
car.removeAction(forKey: "carDrive")
}
}
func moveCar(toPosition position: CGPoint) {
let moveCarToXPoint = SKAction.moveTo(x: position.x, duration: 1)
car.run(moveCarToXPoint, withKey: "carDrive")
}
}

Change child parent in GameKit

I am working on an arrow shooting game - The player need to shoot 3 arrows to a moving target (the target moves from left to right). When an arrow hits the target it should move with it (left to right). The most obvious thing to do would be to change the arrow parent to the target. From some reason its causing me some troubles -
I tried --- arrow.move(toParent:target) and I don't see the arrow on the screen even after I set a new location for it
If I simply --- target.addChild(arrow) I get a failure since I did not remove the arrow from its parent (which is the scene in this case)
When I --- arrow.removeFromParent() and then target.addChild(arrow) its causing other arrows to collide with each other and I still don't see the arrow on the screen.
This is my code -
class GameScene: SKScene, SKPhysicsContactDelegate {
var target:SKSpriteNode?
var arrows = [SKSpriteNode]()
var arrowContactPoint:CGPoint?
let noCategory:UInt32 = 0
let arrowCategory:UInt32 = 0b1
let targetCategory:UInt32 = 0b1 << 1
let obstacleCategory:UInt32 = 0b1 << 2
override func didMove(to view: SKView) {
allowCollisionDetection()
setTarget()
moveTargetFromSideToSide()
newArrow()
}
func didBegin(_ contact: SKPhysicsContact) {
let categoryBitMaskBodyA:UInt32 = contact.bodyA.categoryBitMask
let categoryBitMaskBodyB:UInt32 = contact.bodyB.categoryBitMask
if ((categoryBitMaskBodyA == targetCategory && categoryBitMaskBodyB == arrowCategory) || (categoryBitMaskBodyA == arrowCategory && categoryBitMaskBodyB == targetCategory)) {
arrowContactPoint = contact.contactPoint
arrowCollideWithTarget()
} else if (categoryBitMaskBodyA == obstacleCategory || categoryBitMaskBodyB == obstacleCategory) {
let obstacleNode:SKNode = ((categoryBitMaskBodyA == arrowCategory) ? contact.bodyA.node! : contact.bodyB.node)!
arrowCollideWithObstacle(obstacle:obstacleNode)
} else if (categoryBitMaskBodyA == arrowCategory && categoryBitMaskBodyB == arrowCategory) {
newGame()
} else {
print("Something went wrong")
}
newArrow()
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
shootArrow()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
func allowCollisionDetection() {
self.physicsWorld.contactDelegate = self
}
func setTarget() {
target = self.childNode(withName: "target") as? SKSpriteNode
//Set the target bit mask, it's tag
target?.physicsBody?.categoryBitMask = targetCategory
//Set with which objects the target collide
target?.physicsBody?.collisionBitMask = noCategory
//Set to which coliision we want to responde/handle - didBegin will get triggered
target?.physicsBody?.contactTestBitMask = arrowCategory
}
func moveTargetFromSideToSide() {
let moveRight = SKAction.moveBy(x: frame.size.width - (target?.size.width)!, y: 0, duration: 2)
let moveLeft = SKAction.moveBy(x: -(frame.size.width - (target?.size.width)!), y: 0, duration: 2)
let moveBackAndForth = SKAction.repeatForever(SKAction.sequence([moveRight, moveLeft]))
target?.run(moveBackAndForth)
}
func newArrow() {
let arrow = SKSpriteNode(imageNamed: "arrow1")
let arrowTexture = SKTexture(imageNamed: "arrow1")
arrow.position = CGPoint.zero
self.addChild(arrow)
arrow.physicsBody = SKPhysicsBody(texture: arrowTexture, size: arrowTexture.size())
arrow.physicsBody?.isDynamic = true
arrow.physicsBody?.allowsRotation = true
arrow.physicsBody?.affectedByGravity = false
arrow.physicsBody?.friction = 0.2
arrow.physicsBody?.restitution = 0.2
arrow.physicsBody?.linearDamping = 0.1
arrow.physicsBody?.angularDamping = 0.1
arrow.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
arrow.physicsBody?.categoryBitMask = arrowCategory
arrow.physicsBody?.collisionBitMask = noCategory
arrow.physicsBody?.contactTestBitMask = arrowCategory | obstacleCategory | targetCategory
arrows.append(arrow)
}
func shootArrow(){
print("shootArrow")
arrows.last!.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 80))
}
func arrowCollideWithTarget() {
print("arrowCollideWithTarget")
arrows.last!.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
arrows.last!.move(toParent: target!)
}
func arrowCollideWithObstacle(obstacle:SKNode) {
print("arrowCollideWithObstacle")
arrows.last!.removeFromParent()
arrows.removeLast()
}
func newGame() {
print("New Game")
for i in 0 ..< (arrows.count) {
arrows[i].removeFromParent()
}
arrows.removeAll()
}
}
What eventually solved it for me was using this method ---
move(toParent: )
This is my code -
func arrowCollideWithTarget() {
arrows.last!.move(toParent:target!)
}

Move sprite forever

I am trying to move sprite to the right when I press a button on the screen. However, when I try doing it I only have a solution to move the sprite to a certain point. So... I want the sprite to move to the right forever or until i do something else.
This is in Xcode using Swift in SpriteKit.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch : AnyObject in touches{
let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
let tappeNodeName = tappedNode.name
if tappeNodeName == "Btn"{
player.physicsBody?.velocity = CGVectorMake(0, 0)
let action = SKAction.applyImpulse(CGVectorMake(400, 0), duration: 1)
player.runAction(SKAction.repeatActionForever(action))
print("Touched!")
}
}
}
You can simply move your node to the right untill it does exist the scene
class GameScene: SKScene {
private var player: SKSpriteNode!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
if tappedNode.name == "Btn"{
let moveToRight = SKAction.moveToX(self.frame.width + player.frame.width, duration: 5)
player.runAction(moveToRight)
}
}
}
Update: constant speed
If you want the player to move with constant speed you can use this code.
As you can see I am calculating the duration using space / speed. You just need to find the best constant value for speed for your scenario.
class GameScene: SKScene {
private var player: SKSpriteNode!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
let deltaX = self.frame.width + player.frame.width - player.position.x
let speed: CGFloat = 10 // <-- change this to find the best value for you
let duration: NSTimeInterval = NSTimeInterval(deltaX / speed)
if tappedNode.name == "Btn"{
let moveToRight = SKAction.moveByX(deltaX, y:0, duration: duration)
player.runAction(moveToRight)
}
}
}

Multiple circles drawn SpriteKit

I'm working on simple game which will based on paiting background by player. In left and right corner there will be buttons which will move character to left or right. I've already implemented that (character is moving and lefts painted background behind), but with adding another circles fps's drops really fast. Is there any solution to that?
import SpriteKit
class GameScene: SKScene {
var playerDot:PlayerDot = PlayerDot(imageNamed:"player")
var isTurningLeft:Bool = false
var isTurningRight:Bool = false
var lastLocation:CGPoint = CGPoint()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Helvetica")
myLabel.name = "left"
myLabel.text = "Left"
myLabel.fontSize = 30
myLabel.horizontalAlignmentMode = .Left
myLabel.position = CGPoint(x:CGRectGetMinX(self.frame), y:CGRectGetMinY(self.frame))
self.addChild(myLabel)
let myLabel2 = SKLabelNode(fontNamed:"Helvetica")
myLabel2.name = "right"
myLabel2.text = "Right"
myLabel2.fontSize = 30
myLabel2.horizontalAlignmentMode = .Right
myLabel2.position = CGPoint(x:CGRectGetMaxX(self.frame), y:CGRectGetMinY(self.frame))
self.addChild(myLabel2)
playerDot.position = CGPoint(x:CGRectGetMaxX(self.frame)/2, y:CGRectGetMinY(self.frame))
self.addChild(playerDot)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "left" {
isTurningLeft = true
isTurningRight = false
}
else if theName == "right" {
isTurningRight = true
isTurningLeft = false
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "left" {
isTurningLeft = false
}
else if theName == "right" {
isTurningRight = false
}
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "left" {
isTurningLeft = false
}
else if theName == "right" {
isTurningRight = false
}
}
}
}
override func update(currentTime: CFTimeInterval) {
if(isTurningLeft){
playerDot.increaseAngle()
} else if (isTurningRight){
playerDot.decreaseAngle()
}
//calculates new character position based on angle of movement changed
playerDot.updatePosition()
drawCircle()
}
func drawCircle(){
if(distanceFromCGPoints(lastLocation, b: playerDot.position)>2){
let circle = SKShapeNode(circleOfRadius: 10 )
circle.position = playerDot.position
circle.fillColor = SKColor.orangeColor()
circle.strokeColor = SKColor.orangeColor()
self.addChild(circle)
lastLocation = playerDot.position
}
}
func distanceFromCGPoints(a:CGPoint,b:CGPoint)->CGFloat{
return sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2));
}
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
}
EDIT:
drawCircle with SKShapeNode replaced with SKSpriteNote
func drawCircle(){
if(distanceFromCGPoints(lastLocation, b: playerDot.position)>2){
let playerDot2 = SKSpriteNode(imageNamed:"player")
playerDot2.position = playerDot.position
self.addChild(playerDot2)
lastLocation = playerDot.position
}
}
If you are having frame rate drops then some parts of your code are slowing down execution too much. You need to optimise your code. Use Instruments (Time Profiler) to find out which lines/functions are causing problems speed wise. If you have never used it before read up on it and use it a couple times to get the gist, then I recommend watching the WWDC video Profiling In-Depth
Based on your edit (switching to SKSpriteNode), this is how you could do it:
Declare a texture as a property of your scene. This way, you load it once and reuse it later:
let yourTexture = SKTextureAtlas(named: "yourAtlas").textureNamed("yourTexture")
Then in your drawCircle method:
func drawCircle(){
if(distanceFromCGPoints(lastLocation, b: playerDot.position)>2){
let playerDot2 = SKSpriteNode(texture: yourTexture)
playerDot2.position = playerDot.position
self.addChild(playerDot2)
lastLocation = playerDot.position
}
}
This way (by using SKSpriteNode instead of SKShapeNode) you have reduced number of draw calls required to render all those circles. Also because you are reusing the same texture, instead of allocating it every time using imageNamed you have reduced greatly an amount of memory that app consumes. Now, SpriteKit can render hundreds of nodes #60 fps if those nodes are rendered in batches. Still there is a limit before fps start dropping. And that depends on a device.

Creating a "wall" node in SpriteKit

I'm working with SpriteKit, Xcode 6 and Swift
I have a spritenode declared like this:
let firstCircle = SKSpriteNode(imageNamed: "Circle")
firstCircle.physicsBody = SKPhysicsBody(circleOfRadius: 7)
firstCircle.physicsBody?.affectedByGravity = false
and another spritenode which is bigger circle declared like this :
let wall = SKSpriteNode(imageNamed: "Circle")
wall.physicsBody = SKPhysicsBody(circleOfRadius: 50)
wall.physicsBody?.affectedByGravity = false
The node firstcircle follows my finger and the node wall stay at the middle of the screen, and I want that the two nodes cannot enter in collision together, but with my actual code, firstcircle just cross the wall, what have I to do in order to fix that problem ?
Here is how I move the node :
let scale:CGFloat = 10.0
let damping:CGFloat = 0.94
var departCircleLocation = CGPoint()
var departTouchLocation = CGPoint()
var currentTouchLocation = CGPoint()
var isTouchActive = false
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
isTouchActive = true
for touch: AnyObject in touches
{
departTouchLocation = touch.locationInNode(self)
}
departCircleLocation = firstCircle.position
currentTouchLocation = departTouchLocation
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent)
{
for touch: AnyObject in touches
{
currentTouchLocation = touch.locationInNode(self)
}
moveCircles()
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent)
{
isTouchActive = false
}
override func update(currentTime: NSTimeInterval)
{
moveCircle()
}
func moveCircle()
{
if isTouchActive
{
var dx = CGFloat(departCircleLocation.x - departTouchLocation.x + currentTouchLocation.x - firstCircle.position.x) * scale
var dy = CGFloat(departCircleLocation.y - departTouchLocation.y + currentTouchLocation.y - firstCircle.position.y) * scale
firstCircle.physicsBody?.velocity = CGVectorMake(dx, dy)
}
else
{
let dx = firstCircle.physicsBody!.velocity.dx * damping
let dy = firstCircle.physicsBody!.velocity.dy * damping
firstCircle.physicsBody!.velocity = CGVectorMake(dx, dy)
}
}