I just finished my swift game and I would try it on all devices.
I just note that, before the iPhone 5S, all device doesn't work with arc4random. The iPhone 5 is a 32bit device and arc4randomreturn a UInt32 and it will cause an overflow if the random number is too big. I tried to replace arc4random by arc4random_uniform as onevcat said here.
But still doesn't work.
See my code and a screen shot error bellow :
var lastYieldTimeInterval:NSTimeInterval = NSTimeInterval()
var lastUpdatetimeInterval:NSTimeInterval = NSTimeInterval()
var lastUpdatetimeIntervalBl:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalrou:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalro:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalj:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalvio:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalv:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalora:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervaln:NSTimeInterval = NSTimeInterval()
var lastYieldTimeIntervalGold:NSTimeInterval = NSTimeInterval()
func updateWithTimeSinceLastUpdate(timeSinceLastUpdate:CFTimeInterval){
let minInterval = UInt32(0)
let maxInterval = UInt32(1500)
let rangeInterval = UInt32(maxInterval - minInterval)
lastYieldTimeInterval += timeSinceLastUpdate
let intervalbl = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeInterval > NSTimeInterval(intervalbl)){
lastYieldTimeInterval = 0
addBalloonbl()
}
lastYieldTimeIntervalj += timeSinceLastUpdate
let intervalj = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalj > NSTimeInterval(intervalj)){
lastYieldTimeIntervalj = 0
addBalloonj()
}
lastYieldTimeIntervalora += timeSinceLastUpdate
let intervalora = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalora > NSTimeInterval(intervalora)){
lastYieldTimeIntervalora = 0
addBalloonora()
}
lastYieldTimeIntervalrou += timeSinceLastUpdate
let intervalrou = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalrou > NSTimeInterval(intervalrou)){
lastYieldTimeIntervalrou = 0
addBalloonrou()
}
lastYieldTimeIntervalro += timeSinceLastUpdate
let intervalro = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalro > NSTimeInterval(intervalro)){
lastYieldTimeIntervalro = 0
addBalloonro()
}
lastYieldTimeIntervalvio += timeSinceLastUpdate
let intervalvio = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalvio > NSTimeInterval(intervalvio)){
lastYieldTimeIntervalvio = 0
addBalloonvio()
}
lastYieldTimeIntervalv += timeSinceLastUpdate
let intervalv = Int(arc4random_uniform(rangeInterval)) + Int(minInterval)
if (lastYieldTimeIntervalv > NSTimeInterval(intervalv)){
lastYieldTimeIntervalv = 0
addBalloonv()
}
let minIntervalBl = 1
let maxIntervalBl = 3000
let rangeIntervalBl = maxIntervalBl - minIntervalBl
lastYieldTimeIntervaln += timeSinceLastUpdate
let intervaln = Int(arc4random()) % Int(rangeIntervalBl) + Int(minIntervalBl)
if (lastYieldTimeIntervaln > NSTimeInterval(intervaln)){
lastYieldTimeIntervaln = 0
addBalloonnoir()
}
let minIntervalGold = 4
let maxIntervalGold = 3000
let rangeIntervalGold = maxIntervalGold - minIntervalGold
lastYieldTimeIntervalGold += timeSinceLastUpdate
let intervalGold = Int(arc4random()) % Int(rangeIntervalGold) + Int(minIntervalGold)
if (lastYieldTimeIntervalGold > NSTimeInterval(intervalGold)){
lastYieldTimeIntervalGold = 0
addBalloongold()
}
}
I found why this doesn't work. Actually it is not timesincelastupdate but still the arc4random. I forgot to replace it on two lines. Now Everything is working...
Thank you for your help
Related
I'm just a beginner in Swift but I was trying to implement this particular feature in a project of mine (word search puzzle): selecting multiple cells with a pan gesture. Each of my cells contains a label that holds a single character. I'd like to get all the letters the user wants to select through a pan gesture. Currently I'm doing this by calculating the distance from the center of each cell to the line passing though points a (touch began) and b (touch ended) and taking into consideration only the cells that lie close enough to that line. This works fine most of the time but it's still prone to errors and it is sure to lead to user dissatisfaction. Could you suggest a simpler way of doing this?
Thanks.
Some code:
func getGridInfo(){
for i in 0...numberOfCells-1{
let indPath = IndexPath(row:i, section:0);
let cell = collectionView?.cellForItem(at: indPath) as? CustomCell;
let frameRect = collectionView?.convert((cell?.frame)!, to: self.view);
coordinates[i] = (cell?.label.text, frameRect?.midX, frameRect?.midY) as? (String, CGFloat, CGFloat);
}
}
#objc func handlePan(touch: UIPanGestureRecognizer){
let touchPoint = touch.location(in: self.view)
switch touch.state{
case .began:
if let line = curLine{
line.removeFromSuperlayer();
}
firstPoint = touchPoint;
case .ended:
secondPoint = touchPoint;
guard let fP = firstPoint,
let sP = secondPoint else {
print("Something went wrong..");
return;
}
let word = getCloseLetters(start:fP, end:sP);
if (words.contains(word) || words.contains(String(word.reversed()))){
playSound(soundUrl: correctUrlSoundFx);
foundWordsLabel.text = word;
foundWordsLabel.textColor = UIColor.green;
// to do: update score
}else{
playSound(soundUrl: incorrectUrlSoundFx);
let attributedString = NSMutableAttributedString(string:word);
attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value:2, range: NSMakeRange(0, attributedString.length));
foundWordsLabel.attributedText = attributedString;
foundWordsLabel.textColor = UIColor.red;
}
curLine = addLine(fromPoint: firstPoint!, toPoint: secondPoint!, width:20);
default:
return;
}
func getCloseLetters(start:CGPoint, end:CGPoint) -> String{
var letters = "";
for i in 0...numberOfCells-1{
let tuple = coordinates[i]!;
let x = tuple.1;
let y = tuple.2;
if (checkIfPointIsCloseOrOnTheLine(start: start, end: end, aPoint: CGPoint(x:x,y:y)) == true){
letters += tuple.0;
}
}
return letters;
}
func distanceFromPoint(p: CGPoint, v: CGPoint, w: CGPoint) -> CGFloat {
let pv_dx = p.x - v.x;
let pv_dy = p.y - v.y;
let wv_dx = w.x - v.x;
let wv_dy = w.y - v.y;
let dot = pv_dx * wv_dx + pv_dy * wv_dy;
let len_sq = wv_dx * wv_dx + wv_dy * wv_dy;
let param = dot / len_sq;
var int_x, int_y: CGFloat;
if param < 0 || (v.x == w.x && v.y == w.y) {
int_x = v.x;
int_y = v.y;
} else if param > 1 {
int_x = w.x;
int_y = w.y;
} else {
int_x = v.x + param * wv_dx;
int_y = v.y + param * wv_dy;
}
let dx = p.x - int_x;
let dy = p.y - int_y;
return sqrt(dx * dx + dy * dy);
}
func checkIfPointIsCloseOrOnTheLine(start:CGPoint, end:CGPoint, aPoint:CGPoint, tollerance:CGFloat = 15) -> Bool{
let barHeight = self.navigationController?.navigationBar.frame.size.height;
let newStartPoint = CGPoint(x:start.x, y:start.y - barHeight!);
let newEndPoint = CGPoint(x:end.x, y:end.y - barHeight!);
let distance = distanceFromPoint(p:aPoint, v:newStartPoint, w:newEndPoint);
if distance > tollerance{
return false;
}
return true;
}
Is there a easy way to create a procedural level with a cellular automaton in swift/SpriteKit(library?)? I want to create a 'cave' with 11 fields in the height and 22 width. These should be randomly created and every field without a wall should be reached.
I just found a documentation using Objective-C, which I am not familiar with. I spend quite some time trying to understand the code and follow the example without success.
PS: If there is an easier way I appreciate some algorithms
I made a Playground where you can experiment
//: Playground - noun: a place where people can play
import UIKit
import SpriteKit
import XCPlayground
class Cave {
var cellmap:[[Bool]]
let chanceToStartAlive = 35
let deathLimit = 3
let birthLimit = 4
var xCell = 40 // number of cell in x axes
var yCell = 20 // number of cell in y axes
var wCell = 20 // cell width
var hCell = 20 // cell height
init(){
cellmap = Array(count:yCell, repeatedValue:
Array(count:xCell, repeatedValue:false))
cellmap = self.initialiseMap(xCell, yIndex:yCell)
}
func initialiseMap(xIndex:Int, yIndex:Int) -> [[Bool]]{
var map:[[Bool]] = Array(count:yIndex, repeatedValue:
Array(count:xIndex, repeatedValue:false))
for y in 0...(yIndex - 1) {
for x in 0...(xIndex - 1) {
let diceRoll = Int(arc4random_uniform(100))
if diceRoll < chanceToStartAlive {
map[y][x] = true
} else {
map[y][x] = false
}
}
}
return map
}
func addSprite(scene:SKScene){
for (indexY, row) in cellmap.enumerate(){
for (indexX, isWall) in row.enumerate(){
if isWall {
let wall = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: wCell, height: hCell))
wall.position = CGPoint(x: (indexX * wCell) + (wCell / 2) , y: (indexY * hCell) + (hCell / 2) )
scene.addChild(wall)
}
}
}
}
func countAliveNeighbours(x:Int, y:Int) -> Int{
var count = 0
var neighbour_x = 0
var neighbour_y = 0
for i in -1...1 {
for j in -1...1 {
neighbour_x = x + j
neighbour_y = y + i
if(i == 0 && j == 0){
} else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_y >= cellmap.count || neighbour_x >= cellmap[0].count){
count = count + 1
} else if(cellmap[neighbour_y][neighbour_x]){
count = count + 1
}
}
}
return count
}
func applyRules(){
var newMap:[[Bool]] = Array(count:yCell, repeatedValue:
Array(count:xCell, repeatedValue:false))
for y in 0...(cellmap.count - 1) {
for x in 0...(cellmap[0].count - 1) {
let nbs = countAliveNeighbours( x, y: y);
if(cellmap[y][x]){
if(nbs < deathLimit){
newMap[y][x] = false;
}
else{
newMap[y][x] = true;
}
} else{
if(nbs > birthLimit){
newMap[y][x] = true;
}
else{
newMap[y][x] = false;
}
}
}
}
cellmap = newMap
}
}
let view:SKView = SKView(frame: CGRectMake(0, 0, 1024, 768))
XCPShowView("Live View", view: view)
let scene:SKScene = SKScene(size: CGSizeMake(1024, 768))
scene.scaleMode = SKSceneScaleMode.AspectFit
let aCave = Cave()
aCave.applyRules()
aCave.applyRules()
aCave.addSprite(scene)
view.presentScene(scene)
Updated the playground code for Xcode 8 and Swift 3. I swapped the X and Y cell count since you will likely see the view in a "portrait" orientation.
Remember to open the Assistant Editor to view the results. It also takes a little while to execute, so give it a couple of minutes to run the algorithm.
//: Playground - noun: a place where people can play
import UIKit
import SpriteKit
import XCPlayground
import PlaygroundSupport
class Cave {
var cellmap:[[Bool]]
let chanceToStartAlive = 35
let deathLimit = 3
let birthLimit = 4
var xCell = 20 // number of cell in x axes
var yCell = 40 // number of cell in y axes
var wCell = 20 // cell width
var hCell = 20 // cell height
init(){
cellmap = Array(repeating:
Array(repeating:false, count:xCell), count:yCell)
cellmap = self.initialiseMap(xIndex: xCell, yIndex:yCell)
}
func initialiseMap(xIndex:Int, yIndex:Int) -> [[Bool]]{
var map:[[Bool]] = Array(repeating:
Array(repeating:false, count:xIndex), count:yIndex)
for y in 0...(yIndex - 1) {
for x in 0...(xIndex - 1) {
let diceRoll = Int(arc4random_uniform(100))
if diceRoll < chanceToStartAlive {
map[y][x] = true
} else {
map[y][x] = false
}
}
}
return map
}
func addSprite(scene:SKScene){
for (indexY, row) in cellmap.enumerated(){
for (indexX, isWall) in row.enumerated(){
if isWall {
let wall = SKSpriteNode(color: UIColor.red, size: CGSize(width: wCell, height: hCell))
wall.position = CGPoint(x: (indexX * wCell) + (wCell / 2) , y: (indexY * hCell) + (hCell / 2) )
scene.addChild(wall)
}
}
}
}
func countAliveNeighbours(x:Int, y:Int) -> Int{
var count = 0
var neighbour_x = 0
var neighbour_y = 0
for i in -1...1 {
for j in -1...1 {
neighbour_x = x + j
neighbour_y = y + i
if(i == 0 && j == 0){
} else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_y >= cellmap.count || neighbour_x >= cellmap[0].count){
count = count + 1
} else if(cellmap[neighbour_y][neighbour_x]){
count = count + 1
}
}
}
return count
}
func applyRules(){
var newMap:[[Bool]] = Array(repeating:
Array(repeating:false, count:xCell), count:yCell)
for y in 0...(cellmap.count - 1) {
for x in 0...(cellmap[0].count - 1) {
let nbs = countAliveNeighbours( x: x, y: y);
if(cellmap[y][x]){
if(nbs < deathLimit){
newMap[y][x] = false;
}
else{
newMap[y][x] = true;
}
} else{
if(nbs > birthLimit){
newMap[y][x] = true;
}
else{
newMap[y][x] = false;
}
}
}
}
cellmap = newMap
}
}
let view:SKView = SKView(frame: CGRect(x: 0, y: 0, width: 768, height: 1024))
let scene:SKScene = SKScene(size: CGSize(width: 768, height: 1024))
scene.scaleMode = SKSceneScaleMode.aspectFit
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = view
let aCave = Cave()
aCave.applyRules()
aCave.applyRules()
aCave.addSprite(scene: scene)
view.presentScene(scene)
I have a game similar to fruit ninja using Swift -> SpriteKit. Everything is working fine on iOS 8 but on iOS 9 SKEmitterNode is having a bit strange behavior. This is what I get for my blade effect on both:
func emitterNodeWithColor(color:UIColor)->SKEmitterNode {
let emitterNode:SKEmitterNode = SKEmitterNode()
emitterNode.particleTexture = SKTexture(imageNamed: "spark.png")
emitterNode.particleBirthRate = 3000
emitterNode.particleLifetime = 0.2
emitterNode.particleLifetimeRange = 0
emitterNode.particlePositionRange = CGVectorMake(0.0, 0.0)
emitterNode.particleSpeed = 0.0
emitterNode.particleSpeedRange = 0.0
emitterNode.particleAlpha = 0.8
emitterNode.particleAlphaRange = 0.2
emitterNode.particleAlphaSpeed = -0.45
emitterNode.particleScale = 0.5
emitterNode.particleScaleRange = 0.001
emitterNode.particleScaleSpeed = -1
emitterNode.particleRotation = 0
emitterNode.particleRotationRange = 0
emitterNode.particleRotationSpeed = 0
emitterNode.particleColorBlendFactor = 1
emitterNode.particleColorBlendFactorRange = 0
emitterNode.particleColorBlendFactorSpeed = 0
emitterNode.particleColor = color
emitterNode.particleBlendMode = SKBlendMode.Add
return emitterNode
}
let emitter:SKEmitterNode = emitterNodeWithColor(color)
emitter.targetNode = target
emitter.zPosition = 0
tip.addChild(emitter)
This is the method I am using with all the options. It is the same for both but the result is different. Any ideas how can I make the effect in iOS 9 to be the same as iOS 8 ?
I'm facing the exact same issue in my project.
The emitter's performance is low in iOS9 (Metal version not finished?), so Apple shut off the interpolation of the drawing to get back the performance a little (The drawing rate is limited to 60 fps, anything between two frames is not rendered).
My solution is to implement the tail myself, which is simple:
class TailNode: SKSpriteNode {
var tailTexture: SKTexture!
var tailSize: CGSize! = CGSizeMake(30, 30)
var tailColor: SKColor!
var tailBlendMode: SKBlendMode!
var initialAlpha: CGFloat = 0.6
var initialScale: CGFloat = 0
var finalScale: CGFloat = 1
var particleLife: NSTimeInterval = 0.1
var running: Bool = false
var particleAction: SKAction!
var lastParticle: SKSpriteNode?
var battleScene: BattleScene {
return self.scene as! BattleScene
}
convenience init(tailTexture: SKTexture, tailSize: CGSize, tailColor: SKColor, tailBlendMode: SKBlendMode, initialAlpha: CGFloat, initialScale: CGFloat, finalScale: CGFloat, particleLife: NSTimeInterval) {
self.init(texture: nil, color: SKColor.whiteColor(), size: CGSize(width: 0, height: 0))
self.tailTexture = tailTexture
self.tailSize = tailSize
self.tailColor = tailColor
self.tailBlendMode = tailBlendMode
self.initialAlpha = initialAlpha
self.initialScale = initialScale
self.finalScale = finalScale
self.particleLife = particleLife
let fadeAction = SKAction.fadeAlphaTo(0, duration: particleLife)
let scaleAction = SKAction.scaleTo(finalScale, duration: particleLife)
let removeAction = SKAction.removeFromParent()
self.particleAction = SKAction.sequence([SKAction.group([fadeAction, scaleAction]), removeAction])
}
func updateWithTimeSinceLastUpdate(interval: NSTimeInterval) {
if running {
let particlePosition = battleScene.convertPoint(battleScene.convertPoint(self.position, fromNode: self.parent!),
toNode:battleScene.worldLayers[.UnderCharacter]!)
if lastParticle == nil || lastParticle!.parent == nil {
lastParticle = nil
} else {
let lastPosition = lastParticle!.position
let x = lastPosition.x + (particlePosition.x - lastPosition.x)*0.5
let y = lastPosition.y + (particlePosition.y - lastPosition.y)*0.5
newParticleAtPosition(CGPointMake(x, y), withDelay: interval*0.5)
}
lastParticle = newParticleAtPosition(particlePosition, withDelay: interval)
}
}
func newParticleAtPosition(position: CGPoint, withDelay delay: NSTimeInterval) -> SKSpriteNode {
let myParticle = SKSpriteNode(texture: tailTexture, color: tailColor, size: tailSize)
myParticle.colorBlendFactor = 1
myParticle.blendMode = tailBlendMode
myParticle.alpha = initialAlpha
myParticle.setScale(initialScale)
myParticle.position = position
battleScene.addNode(myParticle, atWorldLayer: .UnderCharacter)
myParticle.runAction(SKAction.sequence([SKAction.waitForDuration(delay), particleAction]))
return myParticle
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi I have been trying to solve this problem for a long time, my problem is that my didBeginContact() does not work the "rocket" collides with the "missiles" and they get pushed down but it does not run the function, what can I do to fix it?
Thanks in advance.
//
// PlaysScene.swift
// Pocket Rocket3
//
// Created by Lucas Farleigh on 27/11/2014.
// Copyright (c) 2014 Lucas Farleigh. All rights reserved.
//
import spriteKit
class PlayScene:SKScene, SKPhysicsContactDelegate{
//declaring the node in this scene!
let background = SKSpriteNode(imageNamed: "background")
let bara = SKSpriteNode(imageNamed: "bar6")
let barb = SKSpriteNode(imageNamed: "bar6")
let barc = SKSpriteNode(imageNamed: "bar6")
let bard = SKSpriteNode(imageNamed: "bar6")
let bare = SKSpriteNode(imageNamed: "bar6")
let barf = SKSpriteNode(imageNamed: "bar6")
let barg = SKSpriteNode(imageNamed: "bar6")
let barh = SKSpriteNode(imageNamed: "bar6")
let bari = SKSpriteNode(imageNamed: "bar6")
let barj = SKSpriteNode(imageNamed: "bar6")
let bar1 = SKSpriteNode(imageNamed: "bar6")
let bar2 = SKSpriteNode(imageNamed: "bar6")
let bar3 = SKSpriteNode(imageNamed: "bar6")
let bar4 = SKSpriteNode(imageNamed: "bar6")
let bar5 = SKSpriteNode(imageNamed: "bar6")
let bar6 = SKSpriteNode(imageNamed: "bar6")
let bar7 = SKSpriteNode(imageNamed: "bar6")
let bar8 = SKSpriteNode(imageNamed: "bar6")
let bar9 = SKSpriteNode(imageNamed: "bar6")
let bar10 = SKSpriteNode(imageNamed: "bar6")
let missile1 = SKSpriteNode(imageNamed:"Missile")
let missile2 = SKSpriteNode(imageNamed:"Missile")
let missile3 = SKSpriteNode(imageNamed:"Missile")
let missile4 = SKSpriteNode(imageNamed:"Missile")
let missile5 = SKSpriteNode(imageNamed:"Missile")
let missile6 = SKSpriteNode(imageNamed:"Missile")
let missile7 = SKSpriteNode(imageNamed:"Missile")
let missile8 = SKSpriteNode(imageNamed:"Missile")
let missile9 = SKSpriteNode(imageNamed:"Missile")
let missile10 = SKSpriteNode(imageNamed:"Missile")
let missile11 = SKSpriteNode(imageNamed:"Missile")
let missile12 = SKSpriteNode(imageNamed:"Missile")
let missile13 = SKSpriteNode(imageNamed:"Missile")
let missile14 = SKSpriteNode(imageNamed:"Missile")
let missile15 = SKSpriteNode(imageNamed:"Missile")
let rocket = SKSpriteNode(imageNamed:"rocket")
var leftTouch = false
var rightTouch = false
enum colideType:UInt32{
case rocket = 1
case missile = 2
}
var actionmove = SKAction.moveToY(-150, duration: 15)
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
let print = SKAction.runBlock({
println("moved")
})
let actionmove1 = SKAction.sequence([actionmove,print])
var delay = SKAction.waitForDuration(NSTimeInterval(1.5))
var delchild = SKAction.removeFromParent()
var rand = arc4random_uniform(10)
self.rocket.physicsBody = SKPhysicsBody(rectangleOfSize: self.rocket.size)
self.physicsBody?.categoryBitMask = colideType.rocket.toRaw()
self.physicsBody?.contactTestBitMask = colideType.missile.toRaw()
rocket.physicsBody?.affectedByGravity = false
rocket.physicsBody?.contactTestBitMask = colideType.missile.toRaw()
rocket.physicsBody?.collisionBitMask = colideType.missile.toRaw()
missile1.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile1.size)
missile2.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile2.size)
missile3.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile3.size)
missile4.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile4.size)
missile5.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile5.size)
missile6.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile6.size)
missile7.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile7.size)
missile8.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile8.size)
missile9.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile9.size)
missile10.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile10.size)
missile1.physicsBody?.dynamic = false
missile2.physicsBody?.dynamic = false
missile3.physicsBody?.dynamic = false
missile4.physicsBody?.dynamic = false
missile5.physicsBody?.dynamic = false
missile6.physicsBody?.dynamic = false
missile7.physicsBody?.dynamic = false
missile8.physicsBody?.dynamic = false
missile9.physicsBody?.dynamic = false
missile10.physicsBody?.dynamic = false
missile1.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile2.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile3.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile4.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile5.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile6.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile7.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile8.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile9.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile10.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile1.physicsBody?.affectedByGravity = false
missile2.physicsBody?.affectedByGravity = false
missile3.physicsBody?.affectedByGravity = false
missile4.physicsBody?.affectedByGravity = false
missile5.physicsBody?.affectedByGravity = false
missile6.physicsBody?.affectedByGravity = false
missile7.physicsBody?.affectedByGravity = false
missile8.physicsBody?.affectedByGravity = false
missile9.physicsBody?.affectedByGravity = false
missile10.physicsBody?.affectedByGravity = false
missile1.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile2.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile3.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile4.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile5.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile6.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile7.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile8.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile9.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile10.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile1.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile2.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile3.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile4.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile5.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile6.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile7.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile8.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile9.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile10.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile1.yScale = 0.35
missile2.yScale = 0.35
missile3.yScale = 0.35
missile4.yScale = 0.35
missile5.yScale = 0.35
missile6.yScale = 0.35
missile7.yScale = 0.35
missile8.yScale = 0.35
missile9.yScale = 0.35
missile10.yScale = 0.35
missile1.xScale = 0.6
missile2.xScale = 0.6
missile3.xScale = 0.6
missile4.xScale = 0.6
missile5.xScale = 0.6
missile6.xScale = 0.6
missile7.xScale = 0.6
missile8.xScale = 0.6
missile9.xScale = 0.6
missile10.xScale = 0.6
let delayA = SKAction.waitForDuration(NSTimeInterval(2.0))
let delayB = SKAction.waitForDuration(NSTimeInterval(4.0))
let delayC = SKAction.waitForDuration(NSTimeInterval(6.0))
let delayD = SKAction.waitForDuration(NSTimeInterval(8.0))
let delayE = SKAction.waitForDuration(NSTimeInterval(10.0))
let delayF = SKAction.waitForDuration(NSTimeInterval(12.0))
let delayG = SKAction.waitForDuration(NSTimeInterval(14.0))
let delayH = SKAction.waitForDuration(NSTimeInterval(16.0))
let delayI = SKAction.waitForDuration(NSTimeInterval(18.0))
let delayJ = SKAction.waitForDuration(NSTimeInterval(20.0))
var missile1Hide = SKAction.runBlock({
self.missile1.hidden = true
})
var missile2Hide = SKAction.runBlock({
self.missile2.hidden = true
})
var missile3Hide = SKAction.runBlock({
self.missile3.hidden = true
})
var missile4Hide = SKAction.runBlock({
self.missile4.hidden = true
})
var missile5Hide = SKAction.runBlock({
self.missile5.hidden = true
})
var missile6Hide = SKAction.runBlock({
self.missile6.hidden = true
})
var missile7Hide = SKAction.runBlock({
self.missile7.hidden = true
})
var missile8Hide = SKAction.runBlock({
self.missile8.hidden = true
})
var missile9Hide = SKAction.runBlock({
self.missile9.hidden = true
})
var missile10Hide = SKAction.runBlock({
self.missile10.hidden = true
})
var missile1show = SKAction.runBlock({
self.missile1.hidden = false
})
var missile2show = SKAction.runBlock({
self.missile2.hidden = false
})
var missile3show = SKAction.runBlock({
self.missile3.hidden = false
})
var missile4show = SKAction.runBlock({
self.missile4.hidden = false
})
var missile5show = SKAction.runBlock({
self.missile5.hidden = false
})
var missile6show = SKAction.runBlock({
self.missile6.hidden = false
})
var missile7show = SKAction.runBlock({
self.missile7.hidden = false
})
var missile8show = SKAction.runBlock({
self.missile8.hidden = false
})
var missile9show = SKAction.runBlock({
self.missile9.hidden = false
})
var missile10show = SKAction.runBlock({
self.missile10.hidden = false
})
var position1 = SKAction.runBlock({
println("1")
self.missile1.position = CGPointMake(600,850)
})
var position2 = SKAction.runBlock({
println("2")
self.missile2.position = CGPointMake(300,850)
})
var position3 = SKAction.runBlock({
self.missile3.position = CGPointMake(100,850)
println("3")
})
var position4 = SKAction.runBlock({
println("4")
self.missile4.position = CGPointMake(900,850)
})
var position5 = SKAction.runBlock({
println("5")
self.missile5.position = CGPointMake(300,850)
})
var position6 = SKAction.runBlock({
println("6")
self.missile6.position = CGPointMake(600,850)
})
var position7 = SKAction.runBlock({
println("7")
self.missile7.position = CGPointMake(200,850)
})
var position8 = SKAction.runBlock({
println("8")
self.missile8.position = CGPointMake(600,850)
})
var position9 = SKAction.runBlock({
println("9")
self.missile9.position = CGPointMake(900,850)
})
var position10 = SKAction.runBlock({
println("10")
self.missile10.position = CGPointMake(200,850)
})
let sequence1 = SKAction.sequence([missile1Hide,delayA,position1,missile1show,actionmove])
let sequence2 = SKAction.sequence([missile2Hide,delayB,position2,missile2show,actionmove])
let sequence3 = SKAction.sequence([missile3Hide,delayC,position3,missile3show,actionmove])
let sequence4 = SKAction.sequence([missile4Hide,delayD,position4,missile4show,actionmove])
let sequence5 = SKAction.sequence([missile5Hide,delayE,position5,missile5show,actionmove])
let sequence6 = SKAction.sequence([missile6Hide,delayF,position6,missile6show,actionmove])
let sequence7 = SKAction.sequence([missile7Hide,delayG,position7,missile7show,actionmove])
let sequence8 = SKAction.sequence([missile8Hide,delayH,position8,missile8show,actionmove])
let sequence9 = SKAction.sequence([missile9Hide,delayI,position9,missile9show,actionmove])
let sequence10 = SKAction.sequence([missile10Hide,delayJ,position10,missile10show,actionmove])
let s1 = SKAction.sequence([delayA,position1,actionmove1])
let s2 = SKAction.sequence([delayB,position2,actionmove1])
let s3 = SKAction.sequence([delayC,position3,actionmove1])
let s4 = SKAction.sequence([delayD,position4,actionmove1])
let s5 = SKAction.sequence([delayE,position5,actionmove1])
let s6 = SKAction.sequence([delayF,position6,actionmove1])
let s7 = SKAction.sequence([delayG,position7,actionmove1])
let s8 = SKAction.sequence([delayH,position8,actionmove1])
let s9 = SKAction.sequence([delayI,position9,actionmove1])
let s10 = SKAction.sequence([delayJ,position10,actionmove1])
let r1 = SKAction.repeatActionForever(s1)
let r2 = SKAction.repeatActionForever(s2)
let r3 = SKAction.repeatActionForever(s3)
let r4 = SKAction.repeatActionForever(s4)
let r5 = SKAction.repeatActionForever(s5)
let r6 = SKAction.repeatActionForever(s6)
let r7 = SKAction.repeatActionForever(s7)
let r8 = SKAction.repeatActionForever(s8)
let r9 = SKAction.repeatActionForever(s9)
let r10 = SKAction.repeatActionForever(s10)
//actionmove: making it smooth
//doing stuff with the background
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
background.yScale = 10.0
background.xScale = 10.0
addChild(background)
addChild(rocket)
rocket.yScale = 0.3
rocket.xScale = 0.6
addChild(missile1)
addChild(missile2)
addChild(missile3)
addChild(missile4)
addChild(missile5)
addChild(missile6)
addChild(missile7)
addChild(missile8)
addChild(missile9)
addChild(missile10)
self.missile1.runAction(r1, completion:{
self.missile1.runAction(r1)
})
self.missile2.runAction(r2, completion:{
self.missile1.runAction(r2)
})
self.missile3.runAction(r3, completion:{
self.missile1.runAction(r3)
})
self.missile4.runAction(r4, completion:{
self.missile1.runAction(r4)
})
self.missile5.runAction(r5, completion:{
self.missile1.runAction(r5)
})
self.missile6.runAction(r6, completion:{
self.missile1.runAction(r6) })
self.missile7.runAction(r7, completion:{
self.missile1.runAction(r7)
})
self.missile8.runAction(r8, completion:{
self.missile1.runAction(r8)
})
self.missile9.runAction(r9, completion:{
self.missile1.runAction(r9)
})
self.missile10.runAction(r10, completion:{
self.missile1.runAction(r10)
})
rocket.position = CGPointMake(CGRectGetMidX(self.frame), 200)
func didBeginContact(contact: SKPhysicsContact){
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene{
let skView = self.view as SKView!
skView.presentScene(scene)
}
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches {
let location = touch.locationInNode(self)
var node = self.nodeAtPoint(location)
var loc = location.x
var tapLoc = SKAction.moveToX(loc, duration: 3.5)
tapLoc.timingMode = SKActionTimingMode.EaseOut
rocket.runAction(tapLoc)
}
}
}
I believe you are missing in didMoveToView:
//not sure if it is needed but almost everyone sets the gravity to 0,0 unless needed
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
Also didBeginContact should be outside of didMoveToView and you have it inside.
Hopefully that helps.
I'm following this tutorial Tutorial space game, and I'm getting this: Thread 1: BAD_EXEC_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0). Everything freezes after, the first parts are ok I see the ship and the background, but when the enemies are supposed to come out the exception is thrown. The code is the following:
func addAlien() {
var alien: SKSpriteNode = SKSpriteNode(imageNamed: "alien")
alien.physicsBody = SKPhysicsBody(rectangleOfSize: alien.size)
alien.physicsBody.dynamic = true
alien.physicsBody.categoryBitMask = alienCategory
alien.physicsBody.contactTestBitMask = photonTorpedoCategory
alien.physicsBody.collisionBitMask = 0
let minX = alien.size.width/2
let maxX = self.frame.size.width - alien.size.width/2
let rangeX = maxX - minX
var position:CGFloat = CGFloat(Int(arc4random())) % CGFloat(rangeX) + CGFloat(minX)
alien.position = CGPointMake(position, self.frame.size.height + alien.size.height)
self.addChild(alien)
let minDuration = 2
let maxDuration = 4
let rangeOfDuration = maxDuration - minDuration
var duration = Int(arc4random()) % Int(rangeOfDuration) + Int(minDuration)
var actionArray: NSMutableArray = NSMutableArray()
actionArray.addObject(SKAction.moveTo(CGPointMake(position, -alien.size.height), duration: NSTimeInterval(duration))) <------- Exception in this line
actionArray.addObject(SKAction.removeFromParent())
alien.runAction(SKAction.sequence(actionArray))
//alien.runAction(SKAction.sequence(actionArray))
}
And I do not know what is wrong, the same was in another tutorial game. The function addAlien() is being called from:
func updateWithTimeSinceLastUpdate(timeSinceLastUpdate: CFTimeInterval) {
lastYieldInterval += timeSinceLastUpdate
if lastYieldInterval > 1 {
lastYieldInterval = 0
addAlien()
}
}
Any help? Thanks.
EDIT: What XCode looks like.
I had the same issue with this tutorial.
I've fixed that exception modifying the duration using this code:
var duration = UInt32(arc4random()) % UInt32(rangeDuration) + UInt32(maxDuration)