How do I run a function inside an action in Sprite Kit? - ios

I have the following code for a game I am making. In one of the parts, I have
let spawn = SKAction.run {
self.createCars()
}
but for some reason I keep getting an error saying "Value of type '(NSObject -> () -> GameScene' has no member 'createCars' even though createCars is a function defined lower in my code. Why is this happening and what can I do to fix this?
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var lanecounter:CGFloat = 0
var score:Int = 0
var player:SKSpriteNode?
let scoreLabel = SKLabelNode()
let highScoreLabel = SKLabelNode()
var direction:Int?
let noCategory:UInt32 = 0
let carCategory:UInt32 = 0b1
let playerCategory:UInt32 = 0b1 << 1
let pointCategory:UInt32 = 0b1 << 2
var died:Bool?
var restartBTN = SKSpriteNode()
let moveLeft:SKAction = SKAction.moveBy(x: -100, y: 0, duration: 0.065)
let moveRight:SKAction = SKAction.moveBy(x: 100, y: 0, duration: 0.065)
let moveDown:SKAction = SKAction.moveTo(y: -800, duration: 1.1)
let spawn = SKAction.run {
self.createCars()
}
let delay = SKAction.wait(forDuration: 4)
func createCars(){
let middlePoints = SKSpriteNode()
var openLane:CGFloat = 0
middlePoints.size = CGSize(width: 100, height: 10)
middlePoints.physicsBody = SKPhysicsBody(rectangleOf: middlePoints.size)
//middlePoints.color = SKColor.purple
middlePoints.physicsBody?.categoryBitMask = pointCategory
middlePoints.physicsBody?.collisionBitMask = playerCategory
middlePoints.physicsBody?.contactTestBitMask = playerCategory
var randInt:Int = 0
randInt = Int(arc4random_uniform(3))
if lanecounter == -2 {
if randInt == 0 || randInt == 1 {
openLane = -1
}
if randInt == 2 {
openLane = -2
}
}
if lanecounter == 2 {
if randInt == 0 || randInt == 1 {
openLane = 1
}
if randInt == 2 {
openLane = 2
}
}
if lanecounter == -1 || lanecounter == 0 || lanecounter == 1 {
if randInt == 0 {
openLane = lanecounter - 1
}
if randInt == 1 {
openLane = lanecounter
}
if randInt == 2 {
openLane = lanecounter + 1
}
}
//print("lanecounter is", lanecounter)
//print("open lane is", openLane)
if openLane != -2 {
spawnCar(xCord: -2)
}
if openLane != -1 {
spawnCar(xCord: -1)
}
if openLane != 0 {
spawnCar(xCord: 0)
}
if openLane != 1 {
spawnCar(xCord: 1)
}
if openLane != 2 {
spawnCar(xCord: 2)
}
middlePoints.position = CGPoint(x: (openLane*100), y: self.frame.height)
self.addChild(middlePoints)
middlePoints.run(moveDown)
}
}

Minimal, Complete, and Verifiable
First of all, we need a Minimal, Complete, and Verifiable example like this:
class GameScene: SKScene {
let spawn = SKAction.run {
self.createCars()
}
func createCars() { }
}
error: value of type '(NSObject) -> () -> GameScene' has no member 'createCars'
Problem
The problem happens because you can't populate a property on the same line it is defined using self (infact self doesn't exist yet).
Solution
However you can use a lazy property wich will be evaluated only when called (and at that time self will be available).
class GameScene: SKScene {
lazy var spawn: SKAction = {
SKAction.run { self.createCars() }
}()
func createCars() { }
}

Related

How to make a number not repeat itself more than 2 times?

everyone ! Lets say we have
let random = arc4random_uniform(6)
how do i make it not repeat the same number more then two times ? I tried doing it like this :
let previousNumber = Int()
let lastNumber = Int ()
let random = Int(arc4random_uniform(6))
if random == previousNumber {
lastNumber = previousNumber
} else {
previousNumber = random
}
if random == lastNumber {
random = Int(arc4random_uniform(6))
}
But it didn't work. I am new to swift and i didn't find a topic about this on the new swift 3 code. Thank you !
First of all lets build a class to save the recent history of the selected values
class History {
private let size: Int
private var values = [Int]()
init(size:Int) {
self.size = size
}
func add(value: Int) {
values.insert(value, at: 0)
if values.count > size {
values.removeLast()
}
}
var repeatedValueOnFullHistory: Int? {
guard Set(values).count <= 1 else { return nil }
return values.first
}
}
Next let build a Randomizer
class Randomizer {
private var allValues = [Int]()
private var history: History
init?(maxValue: Int) {
guard maxValue > 0 else { return nil }
self.allValues = Array(0...maxValue)
self.history = History(size: maxValue + 1)
}
var next: Int {
let excludedValue = history.repeatedValueOnFullHistory
let allowedValues = allValues.filter { excludedValue != $0 }
let randomIndex = Int(arc4random_uniform(UInt32(allowedValues.count)))
let nextValue = allowedValues[randomIndex]
history.add(value: nextValue)
return nextValue
}
}
And finally let test it
if let r = Randomizer(maxValue: 6) {
r.next // 6
r.next // 2
r.next // 1
r.next // 4
r.next // 6
r.next // 4
r.next // 1
}

Make PanGesture becoming to slider

I made a PanGuesture as a slider, Here blow is the responds func:
func respondsToPenGesture(sender: UIPanGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.Began) {
if noFilterEffectButton.selected == false {
startPanLocation = sender.locationInView(self.newEffectView)
persentageNumber.text = String(startNumber)
persentageNumber.hidden = false
}
} else if (sender.state == UIGestureRecognizerState.Changed) {
let stopLocation = sender.locationInView(self.newEffectView)
let abscissaChange = stopLocation.x - startPanLocation!.x
if newEffectView.hidden == false {
if abs(abscissaChange) > 0 {
if noFilterEffectButton.selected == false{
if let effectCurrent = self.currentEffect {
effectCurrent.adjustParams(CGFloat(abscissaChange/6))
}
}
}
if noFilterEffectButton.selected == false {
var printChangingNumber = startNumber + Int(abscissaChange)
if printChangingNumber > 100 {
printChangingNumber = 100
} else if printChangingNumber < 0 {
printChangingNumber = 0
}
persentageNumber.text = String(printChangingNumber)
}
}
} else if (sender.state == UIGestureRecognizerState.Ended) {
let stopLocation = sender.locationInView(self.newEffectView)
let abscissaChange = stopLocation.x - startPanLocation!.x
startNumber = startNumber + Int(abscissaChange)
if startNumber > 100 {
startNumber = 100
} else if startNumber < 0 {
startNumber = 0
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.persentageNumber.text = String(self.startNumber)
self.persentageNumber.hidden = true
}
}
}
percentageNumber is a label show the changes on the screen. And the adjustParams() function:
func adjustParams(value: CGFloat) {
newValue = value + newValue
self.adjust = newValue
print("AdjustNumber")
print(adjust)
}
And I override this function for exactly one effect:
override func adjustParams(value: CGFloat) {
super.adjustParams(value)
lastAutValueChange = lastAutValueChange + value/200
lastIntensityChange = lastIntensityChange + value/200
var currentAutValue = lastAutValueChange
var currentIntValue = lastIntensityChange
currentIntValue = currentIntValue < -1.0 ? -1.0 : currentIntValue
//value = value > 1.0 ? 1.0 : value
//autValue = value < -1.0 ? -1.0 : autValue
if (currentIntValue >= 0) {
currentIntValue = 1.0
} else {
currentIntValue += 1
}
if (currentAutValue <= 0) {
currentAutValue = 0
} else {
if currentAutValue > 1 {
currentAutValue = 1
}
}
print(currentIntValue)
print(currentAutValue)
self.autoTuneModule.setIntensity(Float(currentIntValue))
self.audioUnit.finalMix = Double(currentAutValue)
}
The test answer is not matchable for the exactly changes and the percentNumber shows on the screen. How could I change my functions to make them matchable for each others?
(By the way, I want to do something like the slider in Prisma, if there is something like it, please let me know about it).

Collide type source error - spritekit swift game

So I have adjusted my games ball type from a shape to an image which forced me to redo the physics of my game. I am new to swift and have struggled with fixing my collisions in my swift game.
class GameScene: SKScene, GameDelegate, SKPhysicsContactDelegate {
var ball: Ball!
let ballSpeedX = CGFloat(500)
//ball = Ball(imageNamed:"colorBall.png")
enum CollisionTypes: UInt32 {
case Floor = 1
case Ball = 2
}
// board
let boards = Boards.make(CollideType.BoardStart.rawValue)
var lastBoard: SKNode?
var boardSpeedY: CGFloat { get { return CGFloat(160) * accelerate }}
let boardDistanceY = CGFloat(300)
let boardYDistanceHide = CGFloat(30)
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsWorld.contactDelegate = self
let flooeBody = SKPhysicsBody.init(edgeLoopFromRect: self.frame)
self.physicsBody = floorBody
self.physicsBody!.affectedByGravity = false
self.physicsBody!.usesPreciseCollisionDetection = true
self.physicsBody!.dynamic = true
self.physicsBody!.mass = 0
self.physicsBody!.friction = 0
self.physicsBody!.linearDamping = 0
self.physicsBody!.angularDamping = 0
self.physicsBody!.restitution = 1
self.physicsBody!.categoryBitMask = CollisionTypes.Floor.rawValue
self.physicsBody!.contactTestBitMask = CollisionTypes.Ball.rawValue
// Prepare the ball - physics engine.
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
ball.physicsBody!.affectedByGravity = true
ball.physicsBody!.restitution = 0.8
ball.physicsBody!.linearDamping = 0
ball.physicsBody!.friction = 0.3
ball.physicsBody!.dynamic = true
ball.physicsBody!.mass = 0.5
ball.physicsBody!.allowsRotation = true
ball.physicsBody!.categoryBitMask = CollisionTypes.Ball.rawValue
ball.physicsBody!.contactTestBitMask = CollisionTypes.Floor.rawValue
ball.physicsBody!.collisionBitMask = CollisionTypes.Floor.rawValue
ball.hidden = false
self.addChild(ball)
// scene
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody!.categoryBitMask = CollideType.Scene.toMask()
self.physicsBody!.dynamic = false
self.physicsBody!.friction = 0
// ceil
let ceil = SKShapeNode(rectOfSize: CGSize(width: self.frame.width, height: 2))
ceil.position.x = CGRectGetMidX(self.frame)
ceil.position.y = self.frame.height - CGRectGetMidY(ceil.frame)
ceil.physicsBody = SKPhysicsBody(rectangleOfSize: ceil.frame.size)
ceil.physicsBody!.categoryBitMask = CollideType.Ceil.toMask()
ceil.physicsBody!.dynamic = false
ceil.alpha = 0
self.addChild(ceil)
// floor
let floor = SKShapeNode(rectOfSize: CGSize(width: self.frame.width, height: 2))
floor.position.x = CGRectGetMidX(self.frame)
floor.position.y = CGRectGetMidY(floor.frame)
floor.physicsBody = SKPhysicsBody(rectangleOfSize: floor.frame.size)
//floor.physicsBody!.categoryBitMask = CollideType.Floor.toMask() two
floor.physicsBody!.dynamic = false
floor.alpha = 0
self.addChild(floor)
}
That is the scene and physics I attempted to set up and was directed with. Below is the collide errors which cause the app to crash upon touch.
func didBeginContact(contact: SKPhysicsContact) {
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollisionTypes.Floor.rawValue && contact.bodyB.categoryBitMask == CollisionTypes.Ball.rawValue
let ballAndBoardMask = CollideType.Ball.toMask() | boards.usedCollideMasks
// ball and board error: CANNOT CONVERT VALUE OF TYPE BOOL TO EXPCTD ARG TYPE UIINT32
if bitMaskAAndB | ballAndBoardMask == ballAndBoardMask {
let boardNode: SKNode! = contact.bodyA.categoryBitMask == CollideType.Ball.toMask() ? contact.bodyB.node : contact.bodyA.node
let board = boardNode.bind as! BoardDelegate
board.didBeginContact(boardNode, ball: ball, contact: contact, game: self)
}
// ball and ceil => ERROR
else if bitMaskAAndB == CollideType.toMask([.Ball, .Ceil]) {
stopGame()
}
// ball and floor => stop game
else if bitMaskAAndB == CollideType.toMask([.Ball, .Floor]) {
stopGame()
}
}
func didEndContact(contact: SKPhysicsContact) {
let ballAndBoardMask = CollideType.Ball.toMask() | boards.usedCollideMasks
// ball and board, handle it by board delegate
if contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask | ballAndBoardMask == ballAndBoardMask {
let boardNode: SKNode! = contact.bodyA.categoryBitMask == CollideType.Ball.toMask() ? contact.bodyB.node : contact.bodyA.node
let board = boardNode.bind as! BoardDelegate
board.didEndContact(boardNode, ball: ball, contact: contact, game: self)
}
}
CollideType definition as below:
enum CollideType: Int {
case Scene = 0
case Ceil = 1
case Floor = 2
case Ball = 3
case BoardStart = 4
func toMask()-> UInt32 {
return UInt32(1 << self.rawValue)
}
static func toMask(masks: [CollideType])-> UInt32 {
var toMask = UInt32(0)
for type in masks {
toMask |= type.toMask()
}
return toMask
}
So the issue now is that you have two definition for your masks:
Remove this one:
enum CollisionTypes: UInt32 {
case Floor = 1
case Ball = 2
}
Use only this one:
enum CollideType: Int {
case Scene = 0
case Ceil = 1
case Floor = 2
case Ball = 3
case BoardStart = 4
func toMask()-> UInt32 {
return UInt32(1 << self.rawValue)
}
static func toMask(masks: [CollideType])-> UInt32 {
var toMask = UInt32(0)
for type in masks {
toMask |= type.toMask()
}
return toMask
}
Correct all code to match with CollideType definitions.
Correct this line in didBeginContact:
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollisionTypes.Floor.rawValue && contact.bodyB.categoryBitMask == CollisionTypes.Ball.rawValue
with:
let bitMaskAAndB = contact.bodyA.categoryBitMask == CollideType.Floor.toMask() ? contact.bodyB.categoryBitMask : CollideType.Ball.toMask()
If you have correct all you will don't have yet this error:
// ball and ceil => ERROR

Collect coins and add to score label in Sprite Kit

I'm trying to implement a simple scoring system into my game using this tutorial as a reference:
http://www.raywenderlich.com/87232/make-game-like-mega-jump-sprite-kit-swift-part-2
The problem is, if I try to implement as is, it crashes in the GameScene.swift on this line:
let another = whichNode as! GameObjectNode
Here are the main parts of the code where the player collects the coins. I can also invite you to my repo if you'd like to take a closer and better look. I know it can be hard from looking at the code I pasted up here.
GameObjectNode.swift:
enum CoinType: Int {
case Normal = 0
case Special
}
struct CollisionCategoryBitmask {
static let Player: UInt32 = 0x00
static let Coin: UInt32 = 0x01
static let Platform: UInt32 = 0x02
}
class GameObjectNode: SKNode {
func collisionWithPlayer(player: SKNode) -> Bool {
return false
}
func checkNodeRemoval(playerY: CGFloat) {
if playerY > self.position.y + 300.0 {
self.removeFromParent()
}
}
}
class CoinNode: GameObjectNode {
let coinSound = SKAction.playSoundFileNamed("StarPing.wav", waitForCompletion: false)
var coinType: CoinType!
override func collisionWithPlayer(player: SKNode) -> Bool {
// Boost the player up
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 400.0)
// Play sound
runAction(coinSound, completion: {
// Remove this Star
self.removeFromParent()
})
// Award score
GameState.sharedInstance.score += (coinType == .Normal ? 20 : 100)
// Award stars
GameState.sharedInstance.coins += (coinType == .Normal ? 1 : 5)
// The HUD needs updating to show the new stars and score
return true
}
}
GameState.swift
class GameState {
var score: Int
var highScore: Int
var coins: Int
init() {
// Init
score = 0
highScore = 0
coins = 0
// Load game state
let defaults = NSUserDefaults.standardUserDefaults()
highScore = defaults.integerForKey("highScore")
coins = defaults.integerForKey("coins")
}
func saveState() {
// Update highScore if the current score is greater
highScore = max(score, highScore)
// Store in user defaults
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highScore, forKey: "highScore")
defaults.setInteger(coins, forKey: "coins")
NSUserDefaults.standardUserDefaults().synchronize()
}
class var sharedInstance: GameState {
struct Singleton {
static let instance = GameState()
}
return Singleton.instance
}
}
And the GameScene.swift:
import SpriteKit
import CoreMotion
import GameplayKit
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let PlatformNormal: UInt32 = 0b10 // 2
static let PlatformBreakable: UInt32 = 0b100 // 4
static let CoinNormal: UInt32 = 0b1000 // 8
static let CoinSpecial: UInt32 = 0b10000 // 16
static let Edges: UInt32 = 0b100000 // 32
}
class GameScene: SKScene, SKPhysicsContactDelegate {
// Other Properties
...
var player: SKSpriteNode!
// HUD
var hudNode: SKNode!
var lblScore: SKLabelNode!
var lblCoins: SKLabelNode!
override func didMoveToView(view: SKView) {
....
// HUD
hudNode = SKNode()
hudNode.zPosition = 1000
cameraNode.addChild(hudNode)
// Coins
let coin = SKSpriteNode(imageNamed: "powerup05_1")
coin.position = convertPoint(CGPoint(x: 300, y: self.size.height-100), toNode: cameraNode)
coin.zPosition = 1000
hudNode.addChild(coin)
lblCoins = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblCoins.fontSize = 70
lblCoins.fontColor = SKColor.whiteColor()
lblCoins.position = convertPoint(CGPoint(x: 375, y: self.size.height-100), toNode: cameraNode)
lblCoins.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
lblCoins.zPosition = 1000
lblCoins.text = String(format: "X %d", GameState.sharedInstance.coins)
hudNode.addChild(lblCoins)
// Score
// 4
lblScore = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblScore.fontSize = 70
lblScore.fontColor = SKColor.whiteColor()
lblScore.position = convertPoint(CGPoint(x: self.size.width-325, y: self.size.height-100), toNode: cameraNode)
lblScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right
lblScore.zPosition = 1000
lblScore.text = "0"
hudNode.addChild(lblScore)
}
func setupNodes() {
...
player = fgNode.childNodeWithName("Player") as! SKSpriteNode
}
func createStarAtPosition(position: CGPoint, ofType type: CoinType) -> CoinNode {
// 1
let node = CoinNode()
let thePosition = CGPoint(x: position.x * scaleFactor, y: position.y)
node.position = thePosition
node.name = "NODE_COIN"
// 2
node.coinType = type
var sprite: SKSpriteNode
if type == .Special {
sprite = SKSpriteNode(imageNamed: "CoinSpecial")
} else {
sprite = SKSpriteNode(imageNamed: "Coin")
}
node.addChild(sprite)
// 3
node.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width / 2)
// 4
node.physicsBody?.dynamic = false
node.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Coin
node.physicsBody?.collisionBitMask = 0
node.physicsBody?.contactTestBitMask = 0
return node
}
func didBeginContact(contact: SKPhysicsContact) {
let other = contact.bodyA.categoryBitMask == PhysicsCategory.Player ? contact.bodyB : contact.bodyA
var updateHUD = false
let whichNode = (contact.bodyA.node != player) ? contact.bodyA.node : contact.bodyB.node
// Code crashes here
let another = whichNode as! GameObjectNode
updateHUD = another.collisionWithPlayer(player)
if updateHUD {
lblCoins.text = String(format: "X %d", GameState.sharedInstance.coins)
lblScore.text = String(format: "%d", GameState.sharedInstance.score)
}
switch other.categoryBitMask {
case PhysicsCategory.CoinNormal:
if let coin = other.node as? SKSpriteNode {
emitParticles("CollectNormal", sprite: coin)
jumpPlayer()
runAction(soundCoin)
}
case PhysicsCategory.CoinSpecial:
if let coin = other.node as? SKSpriteNode {
emitParticles("CollectSpecial", sprite: coin)
boostPlayer()
runAction(soundBoost)
}
case PhysicsCategory.PlatformNormal:
if let platform = other.node as? SKSpriteNode {
if player.physicsBody!.velocity.dy < 0 {
platformAction(platform, breakable: false)
jumpPlayer()
runAction(soundJump)
}
}
case PhysicsCategory.PlatformBreakable:
if let platform = other.node as? SKSpriteNode {
if player.physicsBody!.velocity.dy < 0 {
platformAction(platform, breakable: true)
jumpPlayer()
runAction(soundBrick)
}
}
default:
break;
}
}
I dont understand the code you use in didBeganContact, but you can define the contact bodies in this way:
enum Ctg:UInt32
{
case Coin = 1
case Hero = 2
case Villain = 4
case Car = 8
}
var hero = SKSpriteNode()
hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
hero.physicsBody?.categoryBitMask = Ctg.Hero.rawValue
hero.physicsBody?.contactTestBitMask = Ctg.Coin.rawValue | Ctg.Villian.rawValue
var coin = SKSpriteNode()
coin.physicsBody = SKPhysicsBody(rectangleOfSize: coin.size)
coin.physicsBody?.categoryBitMask = Ctg.Coin.rawValue
coin.physicsBody?.contactTestBitMask = Ctg.Hero.rawValue
func didBeginContact(contact: SKPhysicsContact)
{
var first = SKNode()
var sec = SKNode()
// this way you ensure that the first body is the most valuable Ctg (enum)
if contact.bodyA.node?.physicsBody?.categoryBitMask > contact.bodyB.node?.physicsBody?.categoryBitMask
{
first = contact.bodyA.node!
sec = contact.bodyB.node!
}
else
{
first = contact.bodyB.node!
sec = contact.bodyA.node!
}
// this part be sure that the category of first it is of most value that sec
if first.physicsBody!.categoryBitMask == Ctg.Hero.rawValue && sec.physicsBody!.categoryBitMask == Ctg.Coin.rawValue
{
hero.coins++
scene.labelCoins.text = String(coins)
}
if first.physicsBody!.categoryBitMask == Ctg.Villain.rawValue && sec.physicsBody!.categoryBitMask == Ctg.Hero.rawValue
{
gameOver = true
hero.removeFromParent()
lostGame()
}
}

How to make objects exempt from SKcameranode movement

I'm currently developing a scrolling platformer game, and I was wondering how I could have the joystick object move along with the screen but still be useable. Ive tried a number of things, but none of them have produced any viable options. At the moment, the joystick is usable but will scroll off the screen with the rest of the map.
Here is my code:
import SpriteKit
import UIKit
var map = SKNode()
var idleFrames = [SKTexture]()
var walkFrames = [SKTexture]()
var idleFrames1 = [SKTexture]()
var walkFrames1 = [SKTexture]()
var attackFrames1 = [SKTexture]()
var idling = 0
var bullets = 0
var bullet = SKSpriteNode()
var leaf = SKEmitterNode()
var hud: SKSpriteNode?
class GameScene: SKScene, SKPhysicsContactDelegate {
var sp33d: CGVector = CGVectorMake(0.0,0.0)
var knock: CGVector = CGVectorMake(-10.0, 0.0)
var knock1: CGVector = CGVectorMake(10.0, 0.0)
var jsp33d: CGFloat = 170
var gameStick: Joystick?
var player: SKSpriteNode?
var ground: SKSpriteNode?
var ground2: SKSpriteNode?
var ground3: SKSpriteNode?
var canJump = false
var specialbutton = SKSpriteNode(imageNamed: "special")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
hud = self.childNodeWithName("hud") as? SKSpriteNode
gameStick = Joystick()
gameStick?.createJoystick(hud!.frame.width/4, nameBack: "joystick", nameMoving: "joystick1")
gameStick!.backPart!.zPosition = 4
gameStick!.movingPart!.zPosition = 5
map.addChild(gameStick!.backPart!)
map.addChild(gameStick!.movingPart!)
self.addChild(map)
player = self.childNodeWithName("player") as? SKSpriteNode
ground = self.childNodeWithName("testGround") as? SKSpriteNode
ground2 = self.childNodeWithName("testGround2") as? SKSpriteNode
player?.physicsBody?.categoryBitMask = category.player
ground?.physicsBody?.categoryBitMask = category.ground
ground2?.physicsBody?.categoryBitMask = category.ground
player?.physicsBody?.collisionBitMask = category.ground
ground?.physicsBody?.collisionBitMask = category.player
player!.position = CGPoint(x: CGRectGetMidX(self.frame), y: 70)
specialbutton.position = CGPointMake(600, 83)
specialbutton.xScale = 0.165
specialbutton.yScale = 0.165
specialbutton.alpha = 0.5
map.addChild(specialbutton)
camera = self.childNodeWithName("camera") as? SKCameraNode
camera?.position = player!.position
if charnumber == 2{
player?.texture = SKTexture(imageNamed:"Sarah")
}
let idleAtlas = SKTextureAtlas(named: "idle.atlas")
var idleframes = [SKTexture]()
for var i=1; i<=4; i++ {
let idleframe = "JohnIdle\(i)"
idleframes.append(idleAtlas.textureNamed(idleframe))
}
idleFrames = idleframes
let walkAtlas = SKTextureAtlas(named: "jrun.atlas")
var walkframes = [SKTexture]()
for var i=1; i<=8; i++ {
let walkframe = "Johnrun\(i)"
walkframes.append(walkAtlas.textureNamed(walkframe))
}
walkFrames = walkframes
let idleAtlas1 = SKTextureAtlas(named: "Sarahidle.atlas")
var idleframes1 = [SKTexture]()
for var i=1; i<=4; i++ {
let idleframe1 = "SarahIdle\(i)"
idleframes1.append(idleAtlas1.textureNamed(idleframe1))
}
idleFrames1 = idleframes1
let walkAtlas1 = SKTextureAtlas(named: "Sarahrun.atlas")
var walkframes1 = [SKTexture]()
for var i=1; i<=8; i++ {
let walkframe1 = "Sarahrun\(i)"
walkframes1.append(walkAtlas1.textureNamed(walkframe1))
}
walkFrames1 = walkframes1
let attackAtlas1 = SKTextureAtlas(named: "sattack.atlas")
var attackframes1 = [SKTexture]()
for var i=1; i<=9; i++ {
let attackframe1 = "sattack\(i)"
attackframes1.append(attackAtlas1.textureNamed(attackframe1))
}
attackFrames1 = attackframes1
self.physicsWorld.gravity = CGVectorMake(0, -10.0)
self.physicsWorld.contactDelegate = self
}
func didBeginContact(contact:SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == category.player) && (contact.bodyB.categoryBitMask == category.ground) {
idling = 0
johnmove()
print("hit")
canJump = true
}else{
}
}
func didEndContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == category.player) && (contact.bodyB.categoryBitMask == category.ground) {
canJump = false
}
}
func bulletfire(){
bullet = SKSpriteNode(imageNamed: "bullet1")
leaf = SKEmitterNode(fileNamed: "leafParticle")!
bullets = bullets + 1
bullet.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(0.1, 0.1))
bullet.physicsBody?.collisionBitMask = category.ground
bullet.xScale = 0.016
bullet.yScale = 0.016
bullet.physicsBody?.affectedByGravity = false
self.addChild(bullet)
self.addChild(leaf)
if player?.xScale == 1{
bullet.xScale = -0.016
bullet.position.x = (player?.position.x)! + 21.5
bullet.position.y = (player?.position.y)! + 15.4
bullet.physicsBody?.velocity = (CGVectorMake(1000.0, 0.0))
}else{
bullet.position.x = (player?.position.x)! - 21.5
bullet.position.y = (player?.position.y)! + 15.4
bullet.physicsBody?.velocity = (CGVectorMake(-1000.0, 0.0))
}
let action = SKAction.sequence([SKAction.waitForDuration(1), SKAction.removeFromParent()])
bullet.runAction(action, completion: {bullets = bullets - 1})
leaf.runAction(action)
}
func move(){
if player?.xScale == 1 {
player?.size = CGSizeMake(80,80)
player?.position.x = (player?.position.x)! - 20
}else{
player?.size = CGSizeMake(80,80)
player?.position.x = (player?.position.x)! + 20
}
}
func johnmove() {
if charnumber == 1 {
if idling == 1 {
player?.size = CGSizeMake(80,80)
player?.removeActionForKey("idle")
player?.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(walkFrames, timePerFrame: 0.12, resize: false, restore: true)),withKey: "walk")
}
else if idling == 0 {
player?.removeActionForKey("walk")
player?.size = CGSizeMake(80,80)
player?.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(idleFrames, timePerFrame: 0.6, resize: false, restore: true)),withKey: "idle")
}else if idling == 2 {
player?.removeActionForKey("walk")
player?.removeActionForKey("idle")
player?.size = CGSizeMake(80,80)
player?.texture = SKTexture(imageNamed: "JohnJump.png")
}
}else{
sarahhmove()
}
}
func sarahhmove() {
if idling == 1 {
player?.removeActionForKey("idle1")
player?.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(walkFrames1, timePerFrame: 0.12, resize: true, restore: true)),withKey: "walk1")
}
else if idling == 0 {
player?.removeActionForKey("walk1")
player?.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(idleFrames1, timePerFrame: 0.6, resize: false, restore: true)),withKey: "idle1")
}else if idling == 2 {
player?.removeActionForKey("wal1k")
player?.removeActionForKey("idle1")
player?.texture = SKTexture(imageNamed: "SarahJump.png")
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in (touches ) {
let location = touch.locationInNode(self)
var nodeTouched = SKNode()
nodeTouched = self.nodeAtPoint(location)
if nodeTouched.name == "joystick1" {
gameStick?.movingPart?.position = location
if location.x > gameStick!.backPart!.position.x + gameStick!.backPart!.frame.width/2{
gameStick?.movingPart?.position = CGPointMake(gameStick!.backPart!.position.x + gameStick!.backPart!.frame.width/2, gameStick!.movingPart!.position.y)
}
if location.y > gameStick!.backPart!.position.y + gameStick!.backPart!.frame.height/2{
gameStick?.movingPart?.position = CGPointMake(gameStick!.movingPart!.position.x, gameStick!.backPart!.position.y + gameStick!.backPart!.frame.height/2)
}
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in (touches ) {
let location = touch.locationInNode(self)
var nodeTouched = SKNode()
nodeTouched = self.nodeAtPoint(location)
if nodeTouched.name == "joystick1" {
gameStick?.movingPart?.position = location
if location.x > gameStick!.backPart!.position.x + gameStick!.backPart!.frame.width/2{
gameStick?.movingPart?.position = CGPointMake(gameStick!.backPart!.position.x + gameStick!.backPart!.frame.width/2, gameStick!.movingPart!.position.y)
}
if location.y > gameStick!.backPart!.position.y + gameStick!.backPart!.frame.height/2{
gameStick?.movingPart?.position = CGPointMake(gameStick!.movingPart!.position.x, gameStick!.backPart!.position.y + gameStick!.backPart!.frame.height/2)
}
}else if idling == 0 && charnumber == 2{
player?.size = CGSizeMake(80,80)
player?.removeAllActions()
if player?.xScale == 1 {
player?.size = CGSizeMake(80,80)
player?.position.x = (player?.position.x)! + 20
}else{
player?.size = CGSizeMake(80,80)
player?.position.x = (player?.position.x)! - 20
}
player?.size = CGSizeMake(80,80)
player?.runAction(SKAction.repeatAction(SKAction.animateWithTextures(attackFrames1, timePerFrame: 0.09, resize: true, restore: true),count: 1),completion: {self.move()})
player?.size = CGSizeMake(80,80)
player?.texture = SKTexture(imageNamed: "Sarah")
}else if charnumber == 1 && idling == 0{
player?.removeAllActions()
bulletfire()
let yrand = (arc4random_uniform(100) + 50)
let xrand = (arc4random_uniform(300) + 80)
let cartridge = SKSpriteNode(imageNamed: "casing")
cartridge.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(0.1, 0.1))
cartridge.physicsBody?.collisionBitMask = category.ground
cartridge.xScale = 0.05
cartridge.yScale = 0.05
cartridge.zPosition = 3
cartridge.physicsBody?.restitution = 0.5
let spin = SKAction.rotateByAngle(CGFloat(M_PI), duration:0.6)
cartridge.runAction(SKAction.repeatActionForever(spin))
cartridge.physicsBody?.dynamic = true
let flash = SKEmitterNode(fileNamed: "muzzleFlash")
if player?.xScale == 1{
leaf.xScale = -1
flash?.position.x = (player?.position.x)! + 40
flash?.position.y = (player?.position.y)! + 15.3
cartridge.position.x = (player?.position.x)! + 27
cartridge.position.y = (player?.position.y)! + 15.3
player?.physicsBody?.applyImpulse(knock)
cartridge.physicsBody?.velocity = CGVectorMake(-CGFloat(yrand), CGFloat(xrand))
}else{
flash?.position.x = (player?.position.x)! - 40
flash?.position.y = (player?.position.y)! + 15.3
flash?.xAcceleration = -5000
cartridge.position.x = (player?.position.x)! - 27
cartridge.position.y = (player?.position.y)! + 15.3
player?.physicsBody?.applyImpulse(knock1)
cartridge.physicsBody?.velocity = CGVectorMake(CGFloat(yrand), CGFloat(xrand))
}
flash?.zPosition = 3
flash?.xScale = 0.15
flash?.yScale = 0.15
self.addChild(flash!)
self.addChild(cartridge)
let action = SKAction.sequence([SKAction.waitForDuration(0.15), SKAction.removeFromParent()])
let action1 = SKAction.sequence([SKAction.waitForDuration(1.5), SKAction.removeFromParent()])
flash?.runAction(action)
cartridge.runAction(action1)
johnmove()
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in (touches ) {
let location = touch.locationInNode(self)
var nodeTouched = SKNode()
nodeTouched = self.nodeAtPoint(location)
if nodeTouched.name == "joystick1" {
let act = SKAction.moveTo(gameStick!.backPart!.position, duration: 0.2)
gameStick?.movingPart?.runAction(act)
}
}
}
override func update(currentTime: CFTimeInterval) {
hud!.position = (camera?.position)!
let action = SKAction.moveTo((player?.position)!, duration: 0.01)
camera!.runAction(action)
player?.size = CGSizeMake(80,80)
leaf.position = bullet.position
print(canJump)
if (sp33d.dx > 1.5 || sp33d.dx < -1.5) && idling != 1 && idling != 2 {
idling = 1
johnmove()
}else if sp33d.dx < 0.1 && sp33d.dx > -0.1 && idling != 0 && idling != 2{
idling = 0
johnmove()
}
if sp33d.dx > 0.1 {
player!.xScale = 1
} else if sp33d.dx < -0.1 {
player!.xScale = -1
}
/* Called before each frame is rendered */
let vX = gameStick!.movingPart!.position.x - gameStick!.backPart!.position.x
let vY: CGFloat = gameStick!.movingPart!.position.y
if vY > gameStick!.backPart!.position.y + 20 && canJump == true{
sp33d = CGVectorMake(vX/13, jsp33d)
idling = 2
johnmove()
}else{
sp33d = CGVectorMake(vX/13, 0)
}
player?.physicsBody?.applyImpulse(sp33d)
}
}
This is the class in which the joystick is created:
import Foundation
import UIKit
import SpriteKit
class Joystick: UIView {
var movingPart: SKSpriteNode?
var backPart: SKSpriteNode?
let speed: CGFloat = 0.4
var joyStickCenter: CGPoint?
func createJoystick(dimensions: CGFloat, nameBack: String, nameMoving: String)
{
backPart = SKSpriteNode(imageNamed: "joystick")
backPart?.size = CGSizeMake(dimensions, dimensions)
backPart?.position = CGPoint(x: backPart!.size.width/2, y: backPart!.size.width/2)
backPart?.name = nameBack
backPart?.alpha = 0.4
movingPart = SKSpriteNode(imageNamed: "joystick")
movingPart?.size = CGSizeMake(dimensions*0.5, dimensions*0.5)
movingPart?.position = backPart!.position
movingPart?.name = nameMoving
movingPart?.alpha = 0.8
joyStickCenter = backPart!.position
}
func getDistance(p1: CGPoint, p2: CGPoint) -> Double
{
let firstPow = p2.x-p1.x
let secondPow = p2.y-p1.y
var squaredAdded = pow(firstPow, 2)
squaredAdded += pow(secondPow, 2)
let theSquirt = sqrt(Double(squaredAdded))
return theSquirt
}
func resetMovingPart()
{
movingPart?.runAction(SKAction.moveTo(joyStickCenter!, duration: 0.4))
}
func calcXYDiff(loc: CGPoint) -> CGPoint
{
let oldMovingPartPoint = movingPart?.position
movingPart?.position = loc
if movingPart!.position.x-joyStickCenter!.x > backPart!.frame.width/2
{
movingPart?.position.x = oldMovingPartPoint!.x
}
if movingPart!.position.y-joyStickCenter!.y > backPart!.frame.height/2
{
movingPart?.position.y = oldMovingPartPoint!.y
}
let x = loc.x - joyStickCenter!.x
let y = loc.y - joyStickCenter!.y
return CGPoint(x: x*speed, y: y*speed)
}
Any help would be greaty appreciated.
Thanks in advance!
Try calling the resetMovingPart() in your update() func.

Resources