SKSpriteNode disappear in GameScene - ios

I'm facing some problem with spritekit in swift.
I was following closely to online tutorials (combining different tutorials into 1 project), trying out the code when I realised my SKSpriteNodes (my "player" and "enemy") sometimes go missing when I try it out on simulator or my iphone.
My situation is kinda similar to this user's problem here, but I don't think my problem lies with the size.
Can anyone enlighten me? Thank you!
Here's my code.
var player : SKSpriteNode!
var backdrop : SKSpriteNode!
var gameTimer : Timer!
var possibleEnemies = ["enemy01", "enemy02", "enemy03"]
let bulletsCategory : UInt32 = 0x1 << 0
let enemyCategory : UInt32 = 0x1 << 1
override func didMove(to view: SKView) {
player = SKSpriteNode(imageNamed: "bird.png")
player.position = CGPoint(x: 0, y: (player.size.height / 2) )
self.addChild(player)
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
self.physicsWorld.contactDelegate = self
self.anchorPoint = CGPoint (x: 0.5 , y: 0)
createBackdrop()
scoreLabel = SKLabelNode(text: "Score: 0")
scoreLabel.position = CGPoint(x: 260, y: self.frame.size.height - 90)
scoreLabel.fontName = "Avenir Book"
scoreLabel.fontSize = 35
scoreLabel.fontColor = UIColor.gray
score = 0
self.addChild(scoreLabel)
gameTimer = Timer.scheduledTimer(timeInterval: 0.75, target: self, selector: #selector(addEnemies), userInfo: nil, repeats: true)
}
#objc func addEnemies() {
possibleEnemies = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleEnemies) as! [String]
let enemy = SKSpriteNode(imageNamed: possibleEnemies[0])
let randomEnemyPosition = GKRandomDistribution(lowestValue: -360, highestValue: 360)
let position = CGFloat(randomEnemyPosition.nextInt())
enemy.position = CGPoint(x: position, y: self.frame.size.height + enemy.size.height)
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.isDynamic = true
enemy.physicsBody?.categoryBitMask = enemyCategory
enemy.physicsBody?.contactTestBitMask = bulletsCategory
enemy.physicsBody?.collisionBitMask = 0
self.addChild(enemy)
let animationDuration : TimeInterval = 6
var actionArray = [SKAction]()
actionArray.append(SKAction.move(to: CGPoint(x: position, y: -enemy.size.height), duration: animationDuration))
actionArray.append(SKAction.removeFromParent())
enemy.run(SKAction.sequence(actionArray))
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
fireBullets()
}
func fireBullets() {
self.run(SKAction.playSoundFileNamed("shoot.wav", waitForCompletion: false))
let bullets = SKSpriteNode(imageNamed: "bullet.png")
bullets.position = player.position
bullets.position.y += 5
bullets.physicsBody = SKPhysicsBody(rectangleOf: bullets.size)
bullets.physicsBody?.isDynamic = true
bullets.physicsBody?.categoryBitMask = bulletsCategory
bullets.physicsBody?.contactTestBitMask = enemyCategory
bullets.physicsBody?.collisionBitMask = 0
bullets.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(bullets)
let animationDuration : TimeInterval = 0.3
var actionArray = [SKAction]()
actionArray.append(SKAction.move(to: CGPoint(x: player.position.x, y: self.frame.size.height + 10), duration: animationDuration))
actionArray.append(SKAction.removeFromParent())
bullets.run(SKAction.sequence(actionArray))
}
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 & bulletsCategory) != 0 && (secondBody.categoryBitMask & enemyCategory) != 0 {
hitByBullets(bulletNode: firstBody.node as! SKSpriteNode, enemyNode: secondBody.node as! SKSpriteNode)
}
}
func hitByBullets (bulletNode: SKSpriteNode, enemyNode: SKSpriteNode) {
let shot = SKEmitterNode(fileNamed: "Magic01")!
shot.position = enemyNode.position
self.addChild(shot)
self.run(SKAction.playSoundFileNamed("shot.mp3", waitForCompletion: false))
bulletNode.removeFromParent()
enemyNode.removeFromParent()
self.run(SKAction.wait(forDuration: 2)) {
shot.removeFromParent()
}
score += 1
}
func touchDown(atPoint pos : CGPoint) {
player.position = pos
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
moveBackdrop()
}

the issue for you sprites not showing up is that none of your objects have a zPosition set on them. You need to layer the objects as you expect them to show in the scene.
for example...
background.zPosition = 1
player.zPosition = 1
enemy.zPosition = 1
bullet.zPosition = 2
scoreLabel.zPosition = 100
In my opinion you shouldn't be using timers to generate your enemies. Spritekit has it's own timing functionality built into the update function. Which you are already using to control the timing of the backgrounds.
You had waaaaay to much code in your question, you need to look at how I've tailored the code down to only relevant code to your question. Including all of your code in your question actually makes it more unlikely that you will get the help or answers you need because it is harder to go through all the code to figure out what is happening. Also don't include so many spaces in your code in your question scrolling through hundreds of lines even if a lot of them are spaces is very tedious.

Didn't realised the importance of zPosition since my items show up perfectly on screen some of the times. Added the following in their respective place and they stop disappearing intermittently.
player.zPosition = 3
scoreLabel.zPosition = 100
enemy.zPosition = 3
bullets.zPosition = 2
backdrop.zPosition = 1
shot.zPosition = 3

Related

Asteroid Battle Game Keep Crashing

So I keep getting this error at random times during the play of the game, "fatal error: unexpectedly found nil while unwrapping an Optional value" in my asteroid battle game. I'll post the code here and if anyone could help figure it out I would appreciate it. If you don't understand any part you can ask me
import SpriteKit
import Darwin
struct PhysicsCatagory {
static let Asteroids : UInt32 = 1 //00000000000000000000000000000001
static let Bullet : UInt32 = 2 //0000000000000000000000000000010
static let Fighter : UInt32 = 3 //0000000000000000000000000000100
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var Score = Int()
var scoreLabel = UILabel()
var Fighter = SKSpriteNode(imageNamed: "Fighter")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
physicsWorld.contactDelegate = self
Fighter.position = CGPointMake(self.size.width / 2, self.size.height / 7)
Fighter.physicsBody = SKPhysicsBody(rectangleOfSize: Fighter.size)
Fighter.physicsBody?.affectedByGravity = false
Fighter.physicsBody?.categoryBitMask = PhysicsCatagory.Fighter
Fighter.physicsBody?.contactTestBitMask = PhysicsCatagory.Asteroids
Fighter.physicsBody?.dynamic = false
var Timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: self, selector: Selector("spawnBullets"), userInfo: nil, repeats: true)
var asteriodsTimer = NSTimer.scheduledTimerWithTimeInterval(0.35 , target: self, selector: Selector("spawnAsteroids"), userInfo: nil, repeats: true)
var furiousAsteriodsTimer = NSTimer.scheduledTimerWithTimeInterval(0.9 , target: self, selector: Selector("spawnFuriousAsteroids"), userInfo: nil, repeats: true)
self.addChild(Fighter)
scoreLabel.text = "\(Score)"
scoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
scoreLabel.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.3)
scoreLabel.textColor = UIColor.whiteColor()
self.view?.addSubview(scoreLabel)
}
func didBeginContact(contact: SKPhysicsContact) {
let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB
if ((firstBody.categoryBitMask == PhysicsCatagory.Asteroids) && (secondBody.categoryBitMask == PhysicsCatagory.Bullet) || (firstBody.categoryBitMask == PhysicsCatagory.Bullet) && (secondBody.categoryBitMask == PhysicsCatagory.Asteroids)){
bulletHitAsteroids(firstBody.node as! SKSpriteNode, Bullet: secondBody.node as! SKSpriteNode)
}
}
func bulletHitAsteroids(Asteroids: SKSpriteNode, Bullet: SKSpriteNode){
Asteroids.removeFromParent()
Bullet.removeFromParent()
Score++
scoreLabel.text = "\(Score)"
}
func bulletHitFuriousAsteroids(FuriousAsteroids: SKSpriteNode, Bullet: SKSpriteNode){
FuriousAsteroids.removeFromParent()
Bullet.removeFromParent()
Score = Score + 2
scoreLabel.text = "\(Score)"
}
func spawnBullets(){
let Bullet = SKSpriteNode(imageNamed: "Bullet")
Bullet.zPosition = -5
Bullet.position = CGPointMake(Fighter.position.x, Fighter.position.y)
let action = SKAction.moveToY(self.size.height + 30, duration: 0.9)
let actionDone = SKAction.removeFromParent()
Bullet.runAction(SKAction.sequence([action, actionDone]))
Bullet.physicsBody = SKPhysicsBody(rectangleOfSize: Bullet.size)
Bullet.physicsBody?.categoryBitMask = PhysicsCatagory.Bullet
Bullet.physicsBody?.contactTestBitMask = PhysicsCatagory.Asteroids
Bullet.physicsBody?.affectedByGravity = false
Bullet.physicsBody?.dynamic = false
self.addChild(Bullet)
}
func spawnAsteroids(){
let Asteroids = SKSpriteNode(imageNamed: "Asteroid")
let minValue = self.size.width / 8
let maxValue = self.size.width - 20
let spawnPoint = UInt32(maxValue - minValue)
Asteroids.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)) , y: self.size.height)
Asteroids.physicsBody = SKPhysicsBody(rectangleOfSize: Asteroids.size)
Asteroids.physicsBody?.categoryBitMask = PhysicsCatagory.Asteroids
Asteroids.physicsBody?.contactTestBitMask = PhysicsCatagory.Bullet
Asteroids.physicsBody?.affectedByGravity = false
Asteroids.physicsBody?.dynamic = true
let action = SKAction.moveToY(-50, duration: 2.5)
let actionDone = SKAction.removeFromParent()
Asteroids.runAction(SKAction.sequence([action, actionDone]))
self.addChild(Asteroids)
}
func spawnFuriousAsteroids(){
let FuriousAsteroids = SKSpriteNode(imageNamed: "FuriousAsteroid")
let minValue = self.size.width / 8
let maxValue = self.size.width - 20
let spawnPoint = UInt32(maxValue - minValue)
FuriousAsteroids.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)) , y: self.size.height)
FuriousAsteroids.physicsBody = SKPhysicsBody(rectangleOfSize: FuriousAsteroids.size)
FuriousAsteroids.physicsBody?.categoryBitMask = PhysicsCatagory.Asteroids
FuriousAsteroids.physicsBody?.contactTestBitMask = PhysicsCatagory.Bullet
FuriousAsteroids.physicsBody?.affectedByGravity = false
FuriousAsteroids.physicsBody?.dynamic = true
let action = SKAction.moveToY(-50, duration: 1.5)
let actionDone = SKAction.removeFromParent()
FuriousAsteroids.runAction(SKAction.sequence([action, actionDone]))
self.addChild(FuriousAsteroids)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
Fighter.position.x = location.x
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
Fighter.position.x = location.x
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
It is crashing because one of the bodies doesn't have its node. When crash happen, try to type something like this in debugger console :
po firstBody.node, or po secondBody.node. One of these two will be nil.
This is happening when more than two bodies make contact as in your example, where you can have a situation where bullet and a two asteroids might be in a contact at the same time. Because SpriteKit can check for a contact only between two bodies at the time, something like this will happen:
didBeginContact is invoked with two physicsBodies passed in (bullet and first asteroide)
now, you are force unwrapping nodes associated with those bodies and removing the asteroid and the bullet from its parent
then, because there are more contacts occurred
didBeginContact is invoked again, with another two physics bodies, but one of those physicsBodies is bullet's physics body again. Another body is , let say furious asteroid.
now, again you are force unwrapping nodes associated with those two physics bodies, but one of them (bullet) is nil.
Solution would be something like this in your didBeginContact method:
if let firstNode = firstBody.node as? SKSpriteNode, let secondNode = secondBody.node as? SKSpriteNode {
bulletHitAsteroids(firstNode, Bullet: secondNode)
}
This way, one bullet will destroy only one asteroid. Which I guess is what you want and what make sense after all.

Setting position of custom SKSpriteNode from GameScene

I am making a custom SKSpriteNode, when I step through calling createShip the heroShip constant in the class is correct, but when I jump back to the gameScene, the heroShip constant there does not have the properties I assigned when calling createShip, I am not sure what I am doing wrong. I have tried using class function but that doesn't work using the height and width properties.
Custom SKSpriteNode class
class hero: SKSpriteNode {
var width: CGFloat = 0.0
var height: CGFloat = 0.0
func createShip() -> SKSpriteNode {
let heroShip = SKSpriteNode(imageNamed: "heroShip")
heroShip.anchorPoint = CGPointMake(1.0, 0.5)
heroShip.physicsBody = SKPhysicsBody(rectangleOfSize: heroShip.size)
heroShip.physicsBody?.usesPreciseCollisionDetection = true
heroShip.zPosition = 1.0
heroShip.physicsBody?.mass = 0.02
heroShip.physicsBody?.dynamic = true
heroShip.physicsBody?.affectedByGravity = false
heroShip.physicsBody?.categoryBitMask = ObjectCategory.collisionHeroCategory.rawValue
heroShip.physicsBody?.contactTestBitMask = ObjectCategory.sceneCategory.rawValue
heroShip.physicsBody?.collisionBitMask = 0x0 | ObjectCategory.sceneCategory.rawValue
//heroShip.position = CGPointMake((scene?.frame.size.width)!/6.0, (scene?.frame.size.height)!/2.0)
heroShip.position = CGPointMake(width, height)
return heroShip
}
}
My GameScene
class GameScene: SKScene,SKPhysicsContactDelegate{
let background = SKSpriteNode(imageNamed: "background")
var score:Int = 0
let scoreLabel = SKLabelNode(fontNamed: "Courier")
let MotionManager = CMMotionManager()
var heroShip = hero()
override func didMoveToView(view: SKView) {
heroShip.width = self.size.width/6.0
heroShip.height = self.size.height/2.0
heroShip.createShip()
let enemyShip = SKSpriteNode(imageNamed: "enemyShip")
/* Setup your scene here */
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRectMake(0,heroShip.size.width/1.25,frame.width,frame.height - heroShip.size.width*1.6))
scene?.physicsBody?.contactTestBitMask = ObjectCategory.sceneCategory.rawValue
scene?.physicsBody?.categoryBitMask = ObjectCategory.sceneCategory.rawValue
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
scoreLabel.fontColor = SKColor.whiteColor()
scoreLabel.text = String(format: "Score: %01u",score)
scoreLabel.position = CGPointMake(frame.size.width/2, frame.size.height - scoreLabel.frame.size.width/1.2)
scoreLabel.zPosition = 1.0
enemyShip.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
enemyShip.zPosition = 1.0
enemyShip.physicsBody = SKPhysicsBody(rectangleOfSize: heroShip.size)
enemyShip.physicsBody?.usesPreciseCollisionDetection = true
enemyShip.physicsBody?.mass = 0.02
enemyShip.physicsBody?.dynamic = true
enemyShip.physicsBody?.affectedByGravity = false
enemyShip.physicsBody?.categoryBitMask = ObjectCategory.collisionEnemyCategory.rawValue
enemyShip.physicsBody?.contactTestBitMask = ObjectCategory.collisionBulletCategory.rawValue
enemyShip.physicsBody?.collisionBitMask = 0x0
self.addChild(enemyShip)
self.addChild(background)
self.addChild(self.heroShip)
self.addChild(scoreLabel)
if MotionManager.accelerometerAvailable{
MotionManager.startAccelerometerUpdates()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let bullet = SKSpriteNode(imageNamed: "bullet")
bullet.position = CGPointMake(heroShip.position.x, heroShip.position.y)
bullet.zPosition = 1.0
// Add physics body for collision detection
bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.frame.size)
bullet.physicsBody?.dynamic = true
bullet.physicsBody?.affectedByGravity = false
bullet.physicsBody?.categoryBitMask = ObjectCategory.collisionBulletCategory.rawValue
bullet.physicsBody?.contactTestBitMask = ObjectCategory.collisionHeroCategory.rawValue
bullet.physicsBody?.collisionBitMask = 0x0;
let action = SKAction.moveToX(CGRectGetMaxX(self.frame) + bullet.size.width, duration: 0.75)
self.addChild(bullet)
bullet.runAction(action, completion: {
bullet.removeAllActions()
bullet.removeFromParent()
})
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyB.categoryBitMask == ObjectCategory.collisionBulletCategory.rawValue && contact.bodyA.categoryBitMask == ObjectCategory.collisionEnemyCategory.rawValue{
score++
}
}
override func update(currentTime: CFTimeInterval) {
let data = MotionManager.accelerometerData
if data?.acceleration.x == nil{
print("nil")
}
else if fabs((data?.acceleration.x)!) > 0.2 {
heroShip.physicsBody?.applyForce(CGVectorMake(0.0, CGFloat(40 * (data?.acceleration.x)!)))
}
scoreLabel.text = String(format: "Score: %01u",score)
}
}
You run
heroShip.createShip()
and then never do anything with the SKSpriteNode that is returned. From what I can tell, the hero class is the hero ship. I am going off of this assumption for the rest of this answer.
Going from the top of the GameScene, you should do some refactoring.
var heroShip = hero() Is going to be replaced to init using the SKSpriteNode structure:
var heroShip = hero(imageNamed: "heroShip")
Moving to hero class, func createShip() -> SKSpriteNode { should be turned into func createShip() {. As you already have the node set up with the image texture now, and are using the hero class as the node, there is no need to return a SKSpriteNode.
Delete let heroShip = SKSpriteNode(imageNamed: "heroShip") as the hero class is going to be our heroShip.
Replace any usage of the heroShip.whatever variable with self.whatever. At the end, delete the return heroShip.
You seem to not be understanding what is happening with your code.
As of right now createShip() is creating a hero ship, but you never use it.
By looking at your code, it seems like createShip() is not even needed. From looking at it, hero IS heroShip, so do the code in your init.
convenience init(imageNamed: String,sceneSize:CGSize) {
let heroTexture = SKTexture(imageNamed: imageNamed)
self.init(texture: heroTexture, color: UIColor.whiteColor(), size: heroTexture.size()) //This may need to be tweeked, my mac is dead right now to verify.
self.anchorPoint = CGPointMake(1.0, 0.5)
self.physicsBody = SKPhysicsBody(rectangleOfSize: self.size)
self.physicsBody?.usesPreciseCollisionDetection = true
self.zPosition = 1.0
self.physicsBody?.mass = 0.02
self.physicsBody?.dynamic = true
self.physicsBody?.affectedByGravity = false
heroShip.physicsBody?.categoryBitMask = ObjectCategory.collisionHeroCategory.rawValue
heroShip.physicsBody?.contactTestBitMask = ObjectCategory.sceneCategory.rawValue
heroShip.physicsBody?.collisionBitMask = 0x0 | ObjectCategory.sceneCategory.rawValue
//self.position = CGPointMake((scene?.frame.size.width)!/6.0, (scene?.frame.size.height)!/2.0)
self.position = CGPointMake(sceneSize.width, sceneSize.height)
}
You now come across another problem, and that is your SKPhysicsBody will not align to your anchor point.
To fix this, create the SKPhysicsBody like this:
let centerPoint = CGPointMake(self.size.width / 2 - (self.size.width * self.anchorPoint.x), self.size.height / 2 - (self.size.height * self.anchorPoint.y))
self.physicsBody = SKPhysicsBody(rectangleOfSize: self.size, center: centerPoint)

Sprite Kit Game Scene changes when it is not supposed to

In a game that I am currently building a person is supposed to catch balls that are falling from the sky. If the ball goes off the screen it means he didn't catch the ball, and so the scene is supposed to change to a game over scene. The problem is that even if the ball doesn't go below the screen the screen will change. But the screen will change to a blank screen so instead of the GameOverScene().
Here is the code for the GameScene()...
//
// GameScene.swift
// catch balls
//
// Created by Ankith Udupa on 8/10/15.
// Copyright (c) 2015 UdupaLabs. All rights reserved.
//
import SpriteKit
var score = 0
var lossFlag = false
class GameScene: SKScene, SKPhysicsContactDelegate {
var person = SKSpriteNode(imageNamed: "guyLeft_1.png")
var left = true
let kScoreHudName = "scoreHud"
struct PhysicsCategory {
static let None : UInt32 = 0
static let All : UInt32 = UInt32.max
static let Ball : UInt32 = 0b1
static let Person: UInt32 = 0b10
}
override func didMoveToView(view: SKView) {
var content = false
//set up screen
setUpScreen()
//set up the physics
physicsWorld.gravity = CGVectorMake(0, 0)
physicsWorld.contactDelegate = self
//add ball
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addBall),
SKAction.waitForDuration(1.0)
])
))
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
left = !left
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if ((person.position.x > person.size.width/2) && (person.position.x < size.width-(person.size.width/2))){
if left {
var leftMove = SKAction.moveByX(5, y: 0, duration: 0.1)
person.runAction(leftMove)
}
if !left { // or use an if-else construct
var rightMove = SKAction.moveByX(-5, y: 0, duration: 0.1)
person.runAction(rightMove)
}
}
}
//random number gen functions
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
//add ball function
func addBall(){
//create ball sprite
var ball = SKSpriteNode(imageNamed: "ball.png")
//create physics for ball
ball.physicsBody = SKPhysicsBody(rectangleOfSize: ball.size) // 1
ball.physicsBody?.dynamic = true // 2
ball.physicsBody?.categoryBitMask = PhysicsCategory.Ball // 3
ball.physicsBody?.contactTestBitMask = PhysicsCategory.Person // 4
ball.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
//generate random postion along x axis for ball to spawn
let actualX = random(min:ball.size.width/2+1, max: size.width - ball.size.width/2-1)
//set balls positon
ball.position = CGPoint(x: actualX, y: size.height - ball.size.width/2)
//add ball to scene
addChild(ball)
//determine speed of ball
let actualDuration = random(min: CGFloat(3.0), max: CGFloat(5.0))
//create movement actions and run them
let actionMove = SKAction.moveTo(CGPoint(x:actualX, y: -ball.size.width/2), duration: NSTimeInterval(actualDuration))
let actionMoveDone = SKAction.removeFromParent()
let Loss = SKAction.runBlock() {
let reveal = SKTransition.crossFadeWithDuration(0.1)
let gameOverScene = GameOverScene()
self.view?.presentScene(GameOverScene(), transition: reveal)
}
ball.runAction(SKAction.sequence([actionMove, Loss, actionMoveDone]))
}
//setUpScreen
func setUpScreen(){
self.backgroundColor = SKColor.whiteColor()
var ground = SKShapeNode(rectOfSize: CGSizeMake(self.frame.size.width, self.frame.size.height * 0.2))
ground.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height * 0.1)
ground.fillColor = SKColor.blueColor()
self.addChild(ground)
person.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height * 0.2)
setUpPersonPhysics()
self.addChild(person)
}
//set up person physics
func setUpPersonPhysics(){
person.physicsBody = SKPhysicsBody(rectangleOfSize: person.size)
person.physicsBody?.dynamic = true
person.physicsBody?.categoryBitMask = PhysicsCategory.Person
person.physicsBody?.contactTestBitMask = PhysicsCategory.Ball
person.physicsBody?.collisionBitMask = PhysicsCategory.None
person.physicsBody?.usesPreciseCollisionDetection = true
}
func didBeginContact(contact: SKPhysicsContact) {
// 1
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
}
// 2
if ((firstBody.categoryBitMask & PhysicsCategory.Ball != 0) &&
(secondBody.categoryBitMask & PhysicsCategory.Person != 0)) {
personDidCollideWithBall(secondBody.node as! SKSpriteNode, ball: firstBody.node as! SKSpriteNode)
}
}
//called when person collides with ball
func personDidCollideWithBall(person:SKSpriteNode, ball:SKSpriteNode) {
println("hit")
ball.removeFromParent()
score++
}
}
and here is the code for the gameOverScene()...
//
// gameOverScene.swift
// catch babies
//
// Created by Ankith Udupa on 8/12/15.
// Copyright (c) 2015 UdupaLabs. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene: SKScene {
var message = "Game Over"
override func didMoveToView(view: SKView) {
self.backgroundColor = SKColor.whiteColor()
setUpTextOutPut()
}
func setUpTextOutPut(){
let gameOverLabel = SKLabelNode(fontNamed: "Superclarendon-Black")
gameOverLabel.text = message
gameOverLabel.fontSize = 40
gameOverLabel.fontColor = SKColor.orangeColor()
gameOverLabel.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(gameOverLabel)
let scoreLabel = SKLabelNode(fontNamed: "Superclarendon-Black")
scoreLabel.text = "\(score)"
scoreLabel.fontSize = 40
scoreLabel.fontColor = SKColor.orangeColor()
scoreLabel.position = CGPoint(x: size.width/2, y: size.height/2-50)
addChild(scoreLabel)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
}
}
The error is with your addBall method,
//add ball function
func addBall(){
//create ball sprite
var ball = SKSpriteNode(imageNamed: "ball.png")
//create physics for ball
ball.physicsBody = SKPhysicsBody(rectangleOfSize: ball.size) // 1
ball.physicsBody?.dynamic = true // 2
ball.physicsBody?.categoryBitMask = PhysicsCategory.Ball // 3
ball.physicsBody?.contactTestBitMask = PhysicsCategory.Person // 4
ball.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
//generate random postion along x axis for ball to spawn
let actualX = random(min:ball.size.width/2+1, max: size.width - ball.size.width/2-1)
//set balls positon
ball.position = CGPoint(x: actualX, y: size.height - ball.size.width/2)
//add ball to scene
addChild(ball)
//determine speed of ball
let actualDuration = random(min: CGFloat(3.0), max: CGFloat(5.0))
//create movement actions and run them
let actionMove = SKAction.moveTo(CGPoint(x:actualX, y: -ball.size.width/2), duration: NSTimeInterval(actualDuration))
let actionMoveDone = SKAction.removeFromParent()
let Loss = SKAction.runBlock() {
let reveal = SKTransition.crossFadeWithDuration(0.1)
let gameOverScene = GameOverScene()
self.view?.presentScene(GameOverScene(), transition: reveal)
}
ball.runAction(SKAction.sequence([actionMove, Loss, actionMoveDone]))
}
If you look at the method properly, you ask to run the sequence to the sprite and inside runBlock, you move to another scene. Do you need to check if the ball is outside bounds inside this block and only then present your game over scene ?
Should it be something like this,
let Loss = SKAction.runBlock() {
if ball.position.x > self.size.width + ball.frame.size.width * 0.5 || ball.position.y < ball.frame.size.height * 0.5 {
let reveal = SKTransition.crossFadeWithDuration(0.1)
let gameOverScene = GameOverScene()
self.view?.presentScene(GameOverScene(), transition: reveal)
}
}

Swift Physics-fatal error: unexpectedly found nil while unwrapping an Optional value when two characters collide

Background on game: Basically you control a character that moves right and left and try to dodge falling blocks. There are three players spawned. One in the middle of the screen, and two exactly size.width away from the middle player on either sides.
This error only happens once in around 10 collisions with the playerRight or playerLeft or Player and falling blocks. As you can see by the screenshot below, the player does not seem to be touching the falling block when it crashes.
Error Code and Screenshots:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_l386_INVOP, subcode=0x0)
How the game scene stopped
I'm thinking it has something to do with how I built the "infinitely" horizontal scrolling player. Basically I have three separate characters and once the middle character goes past size.width or below 0 his position on the screen is changed to the opposite side of the screen essentially making it infinite. Maybe the Player is teleported inside of a block and it gives a nil error. Not really sure but it looks like it has something to do with that. Anyway, heres the relevant code from GameScene.
import SpriteKit
import Foundation
import UIKit
//Collisions
struct PhysicsCategory {
static let Enemy : UInt32 = 1
static let Player : UInt32 = 2
static let PlayerRight : UInt32 = 3
static let PlayerLeft : UInt32 = 4
static let EnemyRight : UInt32 = 5
}
var transition:SKTransition = SKTransition.fadeWithDuration(0.5)
class GameScene: SKScene, SKPhysicsContactDelegate {
//Highscore Variable
var Highscore = Int()
//Score
var Score : Int = 0
var ScoreLabel = UILabel()
//Main Character
var Player = SKSpriteNode(imageNamed: "mainPlayer.png")
//Right-far character
var PlayerRight = SKSpriteNode(imageNamed: "mainPlayer.png")
//Left-far character
var PlayerLeft = SKSpriteNode(imageNamed: "mainPlayer.png")
//Holding vs Tapping Movement of Player
var isTouching = false
var touchXPosition:CGFloat = 0
override func didMoveToView(view: SKView) {
/* Setup your scene here */
//Highscore
var HighscoreDefault = NSUserDefaults.standardUserDefaults()
if (HighscoreDefault.valueForKey("Highscore") != nil) {
Highscore = HighscoreDefault.valueForKey("Highscore") as! NSInteger
}
else {
Highscore = 0
}
//Collisions/Physics
physicsWorld.contactDelegate = self
//Background Color
scene?.backgroundColor = UIColor.blackColor()
//Spawn timer for enemy blocks
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
var scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
//Player coordinates
Player.position.x = size.width * 0.5
Player.position.y = size.width * 0.11 / 2
//Setting Player Sizes
Player.size.width = size.width * 0.11
Player.size.height = size.width * 0.11
PlayerRight.size.width = size.width * 0.11
PlayerRight.size.height = size.width * 0.11
PlayerLeft.size.width = size.width * 0.11
PlayerLeft.size.height = size.width * 0.11
//Initial position of player
Player.position = CGPoint(x: Player.position.x, y: Player.position.y)
//Initial position of far-right player
PlayerRight.position = CGPoint(x: Player.position.x + size.width, y: Player.position.y)
//Initial position of far-left player
PlayerLeft.position = CGPoint(x: Player.position.x - size.width, y: Player.position.y)
//Adding Physics/Collisions to Player
Player.physicsBody = SKPhysicsBody (rectangleOfSize: Player.size)
Player.physicsBody?.affectedByGravity = false
Player.physicsBody?.categoryBitMask = PhysicsCategory.Player
Player.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
Player.physicsBody?.dynamic = false
//Adding Physics/Collisions to PlayerRight
PlayerRight.physicsBody = SKPhysicsBody (rectangleOfSize: PlayerRight.size)
PlayerRight.physicsBody?.affectedByGravity = false
PlayerRight.physicsBody?.categoryBitMask = PhysicsCategory.PlayerRight
PlayerRight.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
PlayerRight.physicsBody?.dynamic = false
//Adding Physics/Collisions to PlayerLeft
PlayerLeft.physicsBody = SKPhysicsBody (rectangleOfSize: PlayerRight.size)
PlayerLeft.physicsBody?.affectedByGravity = false
PlayerLeft.physicsBody?.categoryBitMask = PhysicsCategory.PlayerLeft
PlayerLeft.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
PlayerLeft.physicsBody?.dynamic = false
//Making Players visible
self.addChild(Player)
self.addChild(PlayerRight)
self.addChild(PlayerLeft)
//Making Score Visible
ScoreLabel.text = "\(Score)"
ScoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
ScoreLabel.font = UIFont(name: ScoreLabel.font.fontName, size:20)
ScoreLabel.textColor = UIColor.whiteColor()
self.view?.addSubview(ScoreLabel)
}
func scoreCounter() {
//Setting score
Score += 1
ScoreLabel.text = "\(Score)"
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody = contact.bodyA
var secondBody : SKPhysicsBody = contact.bodyB
//Checking for Player to enemy collisions
if ((firstBody.categoryBitMask == PhysicsCategory.Enemy) && (secondBody.categoryBitMask == PhysicsCategory.Player)){
CollisionWithEnemy(firstBody.node as! SKShapeNode, Player: secondBody.node as! SKSpriteNode)
}
else if (firstBody.categoryBitMask == PhysicsCategory.Player) && (secondBody.categoryBitMask == PhysicsCategory.Enemy) {
CollisionWithEnemy2(firstBody.node as! SKSpriteNode, Enemy: secondBody.node as! SKShapeNode)
}
//Checking for PlayerRight to enemy collisions
if ((firstBody.categoryBitMask == PhysicsCategory.Enemy) && (secondBody.categoryBitMask == PhysicsCategory.PlayerRight)){
CollisionWithEnemy(firstBody.node as! SKShapeNode, Player: secondBody.node as! SKSpriteNode)
}
else if (firstBody.categoryBitMask == PhysicsCategory.PlayerRight) && (secondBody.categoryBitMask == PhysicsCategory.Enemy) {
CollisionWithEnemy2(firstBody.node as! SKSpriteNode, Enemy: secondBody.node as! SKShapeNode)
}
//Checking for PlayerLeft to enemy collisions
if ((firstBody.categoryBitMask == PhysicsCategory.Enemy) && (secondBody.categoryBitMask == PhysicsCategory.PlayerLeft)){
CollisionWithEnemy(firstBody.node as! SKShapeNode, Player: secondBody.node as! SKSpriteNode)
}
else if (firstBody.categoryBitMask == PhysicsCategory.PlayerLeft) && (secondBody.categoryBitMask == PhysicsCategory.Enemy) {
CollisionWithEnemy2(firstBody.node as! SKSpriteNode, Enemy: secondBody.node as! SKShapeNode)
}
}
func CollisionWithEnemy(Enemy: SKShapeNode, Player: SKSpriteNode) {
//Highscore
var ScoreDefault = NSUserDefaults.standardUserDefaults()
ScoreDefault.setValue(Score, forKey: "Score")
ScoreDefault.synchronize()
if (Score > Highscore) {
var HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setValue(Score, forKey: "Highscore")
}
//var gameOver:SKScene = GameOverScene(size: self.size)
//ScoreLabel.removeFromSuperview()
Enemy.removeFromParent()
//Player.removeFromParent()
//self.view?.presentScene(gameOver, transition: transition)
}
func CollisionWithEnemy2(Player: SKSpriteNode, Enemy: SKShapeNode) {
//Highscore
var ScoreDefault = NSUserDefaults.standardUserDefaults()
ScoreDefault.setValue(Score, forKey: "Score")
ScoreDefault.synchronize()
if (Score > Highscore) {
var HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setValue(Score, forKey: "Highscore")
}
//var gameOver:SKScene = GameOverScene(size: self.size)
//ScoreLabel.removeFromSuperview()
Enemy.removeFromParent()
//Player.removeFromParent()
//self.view?.presentScene(gameOver, transition: transition)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
isTouching = true
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
touchXPosition = location.x
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
isTouching = false
}
func spawnEnemies() {
//Randomizing width of blocks
var blockWidth = Int(arc4random_uniform(UInt32(size.width / 3)) + UInt32(size.width / 5))
//Min and Max position of blocks
var minPosition : UInt32 = UInt32(blockWidth / 2)
var maxPosition : UInt32 = UInt32(size.width - CGFloat(blockWidth / 2))
//Randomizing Block Position
var blockXPosition = arc4random_uniform(maxPosition - minPosition) + minPosition
//Making Blocks
var Enemy = SKShapeNode(rectOfSize: CGSize(width: blockWidth, height: 5))
Enemy.position = CGPointMake (CGFloat(blockXPosition), CGFloat(size.height+50))
//Coloring Blocks
Enemy.fillColor = SKColor.whiteColor()
//Moving Blocks
let action = SKAction.moveToY(-50, duration: 2.5)
//Removing blocks once off screen
let actionDone = SKAction.removeFromParent()
//Running the above actions
Enemy.runAction(SKAction.sequence([action, actionDone]))
//Physics/Collisions
Enemy.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize (width: blockWidth, height: 1))
Enemy.physicsBody?.categoryBitMask = PhysicsCategory.Enemy
Enemy.physicsBody?.affectedByGravity = false
Enemy.physicsBody?.dynamic = true
//Adding enemy to scene
self.addChild(Enemy)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
var offsetLeft = 0 - (Player.position.x - 25)
Player.position = CGPoint(x: Player.position.x, y: Player.position.y)
PlayerRight.position = CGPoint(x: Player.position.x + size.width, y: Player.position.y)
PlayerLeft.position = CGPoint(x: Player.position.x - size.width, y: Player.position.y)
if isTouching {
if touchXPosition > self.size.width / 2 {
// move character to the right.
Player.position.x += 10
}
if touchXPosition < self.size.width / 2 {
// move character to the left.
Player.position.x -= 10
}
}
if Player.position.x < 0 {
Player.position.x = size.width
}
if Player.position.x > size.width {
Player.position.x = 0
}
}
}
Everything is commented fairly well but if you have any questions about whats what let me know. Any help with this would be greatly appreciated!
static let PlayerRight : UInt32 = 3 //00000000000000000000000000000100
static let PlayerLeft : UInt32 = 4 //00000000000000000000000000001000
static let EnemyRight : UInt32 = 5 //00000000000000000000000000010000
Do you really believe that 3 is binary 100 and that 4 is binary 1000 (and so on)? Because if you do, and if you need that to be true, you are going to be in huge trouble later if you try to use these values as actual bitmasks.

Sprite Kit set Min. and Max. for Jump

I want to move a SKSpriteNode on the Y-Axis. The SKSpriteNode called Player has no Velocity.The Player can only jump if a Platform is in contact.
Everytime the Screen is touched, I want to give the Player an impulse with a minimum impulse or a maximum impulse
If the Screen is tapped shortly, the Minimum impulse should be e.g. y = 50.
If the Screen is hold, that means the finger is on the Screen long, the Maximum should be e.g. y = 100.
But the Player should be also able to jump between the Minimum and Maximum height, if for e.g. the Screen is not long but also not shortly pressed, the Player should only get an impulse of y = 70.
If the Screen is hold, the Player should jump to his max height, fall down, and if it is in contact with the Platform again, it should jump, because you still hold the Screen.
I have already tried this with the suggested answer in this Thread:StackOverFlow
But this does not give the Minimum jump, also no Press jump.
For clarity: The impulse should not be after the tap is done, but while it is tapped. The longer you hold, the longer the jump is.
import SpriteKit
import GameKit
struct Constants {
static let minimumJumpForce:CGFloat = 40.0
static let maximumJumpForce:CGFloat = 60.0
static let characterSideSpeed:CGFloat = 18.0
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var Player: SKSpriteNode!
var Platform0: SKSpriteNode!
var World: SKNode!
var Camera: SKNode!
var force: CGFloat = 40.0
var pressed = false
var isCharacterOnGround = false
.....
func SpawnPlatforms() {
Platform0 = SKSpriteNode (color: SKColor.greenColor(), size: CGSize(width: self.frame.size.width , height: 25))
Platform0.position = CGPoint(x: self.frame.size.width / 2, y: -36)
Platform0.zPosition = 1
Platform0.physicsBody = SKPhysicsBody(rectangleOfSize:Platform0.size)
Platform0.physicsBody?.dynamic = false
Platform0.physicsBody?.allowsRotation = false
Platform0.physicsBody?.restitution = 0
Platform0.physicsBody?.usesPreciseCollisionDetection = true
Platform0.physicsBody?.categoryBitMask = Platform0Category
Platform0.physicsBody?.collisionBitMask = PlayerCategory
Platform0.physicsBody?.contactTestBitMask = PlayerCategory
World.addChild(Platform0)
}
func SpawnPlayer(){
Player = SKSpriteNode (imageNamed: "Image.png")
Player.size = CGSize(width: 64, height: 64)
Player.position = CGPoint(x: self.frame.size.width / 2, y: 0)
Player.zPosition = 2
Player.physicsBody = SKPhysicsBody(rectangleOfSize:CGSize(width: 35, height: 50))
Player.physicsBody?.dynamic = true
Player.physicsBody?.allowsRotation = false
Player.physicsBody?.restitution = 0.1
Player.physicsBody?.usesPreciseCollisionDetection = true
Player.physicsBody?.categoryBitMask = PlayerCategory
Player.physicsBody?.collisionBitMask = Platform0Category
Player.physicsBody?.contactTestBitMask = Platform0Category | Platform1Category | Platform2Category | Platform3Category | Platform4Category | Platform5Category
World.addChild(Player)
}
func jump(force : CGFloat){
if(self.isCharacterOnGround){
self.Player.physicsBody?.applyImpulse(CGVectorMake(0, force))
self.isCharacterOnGround = false
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
self.pressed = true
let timerAction = SKAction.waitForDuration(0.0)
let update = SKAction.runBlock({
if(self.force < Constants.maximumJumpForce){
self.force += 2.0
}else{
self.jump(Constants.maximumJumpForce)
self.force = Constants.maximumJumpForce
}
})
let sequence = SKAction.sequence([timerAction, update])
let repeat = SKAction.repeatActionForever(sequence)
self.runAction(repeat, withKey:"repeatAction")
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
self.removeActionForKey("repeatAction")
self.jump(self.force)
self.force = Constants.minimumJumpForce
self.pressed = false
}
}
func didBeginContact(contact: SKPhysicsContact) {
//this gets called automatically when two objects begin contact with each other
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch(contactMask) {
case PlayerCategory | Platform0Category:
//either the contactMask was the bro type or the ground type
println("Contact Made0")
Green = true
self.isCharacterOnGround = true
default:
return
}
}
Here is an working example on how to make something like:
long pressed jump based on duration of press
short (one tap jump)
restrict character to jump while in the air
keep character jumping while finger is on screen
Code (Swift 4.x)
import SpriteKit
struct Constants {
static let minimumJumpForce:CGFloat = 15.0
static let maximumJumpForce:CGFloat = 30.0
static let characterSideSpeed:CGFloat = 18.0
}
class GameScene: SKScene,SKPhysicsContactDelegate
{
let CharacterCategory : UInt32 = 0x1 << 1
let PlatformCategory : UInt32 = 0x1 << 2
let WallCategory : UInt32 = 0x1 << 3
var force: CGFloat = 16.0 //Initial force
var pressed = false
var isCharacterOnGround = false // Use this to prevent jumping while in the air
let character = SKSpriteNode(color: .green, size: CGSize(width: 30, height:30))
let debugLabel = SKLabelNode(fontNamed: "Geneva")
override func didMove(to view: SKView)
{
//Setup contact delegate so we can use didBeginContact and didEndContact methods
physicsWorld.contactDelegate = self
physicsWorld.speed = 0.5
//Setup borders so character can't escape from us :-)
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
self.physicsBody?.categoryBitMask = WallCategory
self.physicsBody?.collisionBitMask = CharacterCategory
//Setup character
character.position = CGPoint(x: 150, y: 150)
character.physicsBody = SKPhysicsBody(rectangleOf: character.size)
character.physicsBody?.categoryBitMask = CharacterCategory
character.physicsBody?.contactTestBitMask = PlatformCategory
character.physicsBody?.collisionBitMask = PlatformCategory | WallCategory
character.physicsBody?.allowsRotation = false
character.physicsBody?.isDynamic = true
character.physicsBody?.restitution = 0.1
self.addChild(character)
generatePlatforms()
debugLabel.text = " DEBUG: "
debugLabel.fontColor = .white
debugLabel.fontSize = 12.0
debugLabel.position = CGPoint(x: frame.midX, y: frame.midY+100)
self.addChild(debugLabel)
}
func generatePlatforms(){
for i in 1...4
{
let position = CGPoint(x: frame.midX, y: CGFloat(i)*140.0 - 100)
let platform = createPlatformAtPosition(position: position)
self.addChild(platform)
}
}
func createPlatformAtPosition(position : CGPoint)->SKSpriteNode{
let platform = SKSpriteNode(color: .green, size: CGSize(width: frame.size.width, height:20))
platform.position = position
platform.physicsBody = SKPhysicsBody(
edgeFrom: CGPoint(x: -platform.size.width/2.0, y:platform.size.height/2.0),
to:CGPoint(x: platform.size.width/2.0, y: platform.size.height/2.0))
platform.physicsBody?.categoryBitMask = PlatformCategory
platform.physicsBody?.contactTestBitMask = CharacterCategory
platform.physicsBody?.collisionBitMask = CharacterCategory
platform.physicsBody?.allowsRotation = false
platform.name = "platform"
platform.physicsBody?.isDynamic = false
platform.physicsBody?.restitution = 0.0
return platform
}
func jump(force : CGFloat){
if(self.isCharacterOnGround){
self.character.physicsBody?.applyImpulse(CGVector(dx: 0, dy: force))
self.character.physicsBody?.collisionBitMask = WallCategory
self.isCharacterOnGround = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.pressed = true
let timerAction = SKAction.wait(forDuration: 0.05)
let update = SKAction.run({
if(self.force < Constants.maximumJumpForce){
self.force += 2.0
}else{
self.jump(force: Constants.maximumJumpForce)
self.force = Constants.maximumJumpForce
}
})
let sequence = SKAction.sequence([timerAction, update])
let repeat_seq = SKAction.repeatForever(sequence)
self.run(repeat_seq, withKey:"repeatAction")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.removeAction(forKey: "repeatAction")
self.jump(force: self.force)
self.force = Constants.minimumJumpForce
self.pressed = false
}
override func update(_ currentTime: TimeInterval) {
debugLabel.text = "DEBUG: onTheGround : \(isCharacterOnGround), force \(force)"
if(character.position.x <= character.size.width/2.0 + 5.0 && character.physicsBody!.velocity.dx < 0.0 ){
character.physicsBody?.applyForce(CGVector(dx: Constants.characterSideSpeed, dy: 0.0))
}else if((character.position.x >= self.frame.size.width - character.size.width/2.0 - 5.0) && character.physicsBody!.velocity.dx >= 0.0){
character.physicsBody?.applyForce(CGVector(dx: -Constants.characterSideSpeed, dy: 0.0))
}else if(character.physicsBody!.velocity.dx > 0.0){
character.physicsBody!.applyForce(CGVector(dx: Constants.characterSideSpeed, dy: 0.0))
}else{
character.physicsBody!.applyForce(CGVector(dx: -Constants.characterSideSpeed, dy: 0.0))
}
}
func didBegin(_ contact: SKPhysicsContact) {
var firstBody, 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 & CharacterCategory) != 0 &&
(secondBody.categoryBitMask & PlatformCategory != 0)) {
let platform = secondBody.node! as! SKSpriteNode
// platform.color = UIColor.redColor()
let platformSurfaceYPos = platform.position.y + platform.size.height/2.0
let player = contact.bodyB.node! as! SKSpriteNode
let playerLegsYPos = player.position.y - player.size.height/2.0
if((platformSurfaceYPos <= playerLegsYPos)){
character.physicsBody?.collisionBitMask = PlatformCategory | WallCategory
self.isCharacterOnGround = true
if(self.pressed){
let characterDx = character.physicsBody?.velocity.dx
character.physicsBody?.velocity = CGVector(dx: characterDx!, dy: 0.0)
self.jump(force: Constants.maximumJumpForce)
}
}
}
}
func didEnd(_ contact: SKPhysicsContact) {
var firstBody, 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 & CharacterCategory) != 0 &&
(secondBody.categoryBitMask & PlatformCategory != 0)) {
let platform = secondBody.node as! SKSpriteNode
let platformSurfaceYPos = platform.position.y + platform.size.height/2.0
let player = contact.bodyB.node as! SKSpriteNode
let playerLegsYPos = player.position.y - player.size.height/2.0
if((platformSurfaceYPos <= playerLegsYPos) && ((character.physicsBody?.velocity.dy)! > CGFloat(0.0))){
character.physicsBody?.collisionBitMask = WallCategory
self.isCharacterOnGround = false
}
}
}
}
Note that this is simple example, and in real application you will probably have to handle states like isOnTheGround in a different way. Right now, to determine if character is on the ground you just set isOnTheGround = true when character make a contact with platform, and set it to false in didEndContact...But there are situations when character can be in contact with platform while in the air (eg. side contact)...
EDIT:
I changed the code to let the player jump while pressed. Here is the result:
Important:
Actual platform implementation and contact handling is up to you and this is not tested. The only purpose of this example is to show you how to jump while pressed. Currently, physicsWorld.speed is set to 0.5 to make animation slower because its easier to debug like that, but you can change this to default value (1.0).
So, as you can see from the image, while player is on the first platform some small jumps are presented (by simple tapping, or short pressing). Then (player is still on first platform) long press has been made, and player has jumped on second platform. After that, another long press is done, but this time without releasing, and player starts jumping from one platform to another using maximum force.
This needs a lot of tweaking and proper platform & contact detection, but it can give you an idea about how to implement jumping you asked about.

Resources