Upon initialization of my scene, on rare occasions the app will crash with this error
com.apple.scenekit.scnview-renderer (18): signal SIGABRT
The following is printed in the console
-[MTLTextureDescriptorInternal validateWithDevice:]:1097: failed assertion `MTLTextureDescriptor has invalid pixelFormat (0).'
Lastly, here is the function which is called before the crash
func setupRandomScene() {
self.scene.rootNode.childNodes.forEach({ (node) in
node.removeFromParentNode()
})
DispatchQueue.main.async {
if !Model.shared.hasSeenTooltips {
self.scene = SCNScene(named: "art.scnassets/levels/level\(0).scn")!
} else {
switch Model.shared.level {
case 1...10:
let randomInt = Int.random(in: 1...8)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
case 11...20:
let randomInt = Int.random(in: 1...16)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
default:
let randomInt = Int.random(in: 9...40)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
}
}
let randomColorInt = Int.random(in: 1...4)
switch randomColorInt {
case 1:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/purple")
case 2:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/pink")
case 3:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/orange")
case 4:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/teal")
case 5:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/cyan")
default:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/blue")
}
self.scene.rootNode.childNode(withName: "road", recursively: true)?.geometry?.materials.first?.diffuse.contents = UIColor.black
self.scene.rootNode.childNode(withName: "finishPlatform", recursively: true)?.geometry?.materials.first?.diffuse.contents = UIColor.black
self.scene.rootNode.addChildNode(self.cameraNode)
self.scene.physicsWorld.contactDelegate = self
self.scene.physicsWorld.gravity = SCNVector3(0, -9.8, 0)
self.playerNode = SCNNode()
self.setupPlayerNode()
self.setupSounds()
self.dancingAnimation = SCNAnimation(named: "art.scnassets/stickman/dance\(Int.random(in: 1...10)).scnanim")
let directionalLight = SCNNode()
directionalLight.name = "directional"
directionalLight.position = SCNVector3(-10, 50, -100)
directionalLight.light = SCNLight()
directionalLight.light?.type = .directional
directionalLight.light?.castsShadow = true
directionalLight.light?.shadowRadius = 2 // 1000
directionalLight.light?.shadowSampleCount = 20 // 20
directionalLight.light?.shadowMapSize = CGSize(width: 2000, height: 2000)
directionalLight.light?.intensity = 2000
directionalLight.eulerAngles = SCNVector3(0, -toRadians(angle: 150), -toRadians(angle: 60))
self.scene.rootNode.addChildNode(directionalLight)
let ambientLight = SCNNode()
ambientLight.name = "ambient"
ambientLight.light = SCNLight()
ambientLight.light?.castsShadow = false
ambientLight.light?.type = .ambient
ambientLight.light?.color = UIColor.darkGray
ambientLight.light?.intensity = 5000
self.scene.rootNode.addChildNode(ambientLight)
self.cameraNode.position = SCNVector3(self.playerNode.position.x, self.playerNode.position.y + 5, self.playerNode.position.z - 9)
self.cameraNode.eulerAngles = SCNVector3(-toRadians(angle: 5), -toRadians(angle: 180), 0)
self.cameraNode.camera = SCNCamera()
self.gameState = .menu
self.scnView = nil
self.scnView = self.view as? SCNView
if let _ = self.scnView {
self.scnView!.delegate = self
self.overlayScene = OverlayScene(with: self.overlaySceneSize, isLive: self.broadcastController.isBroadcasting)
self.scnView!.overlaySKScene = self.overlayScene
self.scnView!.present(self.scene, with: .fade(with: .white, duration: 1), incomingPointOfView: nil, completionHandler: nil)
}
if !Model.shared.soundIsMuted {
self.playerNode.runAction(self.playWooshSound)
}
self.positiveHaptic.prepare()
}
}
Related
The following code produces the Error shown in the title of this question on this line : for (index, image) in (backgroundImages) {
can someone advise how to silence this error
init!(backgroundImages:[UIImage], size:CGSize, scrollingDirection:ScrollingDirection, startingSpeed:CGFloat, speedDecreaseFactor:CGFloat) {
self.backgrounds = []
self.clonedBackgrounds = []
self.speeds = []
self.numberOfBackgrounds = (backgroundImages.count)
self.scrollingDirection = scrollingDirection
super.init(texture: nil, color:UIColor.clear, size: size)
let zPos = 1.0 / CGFloat(numberOfBackgrounds)
var currentSpeed = startingSpeed
self.position = CGPoint(x:self.size.width/2, y:self.size.height/2)
self.zPosition = -100
for (index, image) in (backgroundImages) {
let background = SKSpriteNode(texture: SKTexture(CGImage: image.CGImage), size:size)
background.zPosition = self.zPosition - (zPos + (zPos * CGFloat(index)))
background.position = CGPoint(x:0,y:0)
let clonedBackground = background.copy() as! SKSpriteNode
var clonedBackgroundX = background.position.x
var clonedBackgroundY = background.position.y
switch (scrollingDirection) {
case .Right:
clonedBackgroundX = -background.size.width
case .Left:
clonedBackgroundX = background.size.width
default:
break
}
You probably meant for (index, image) in backgroundImages.enumerated()
The compiler can't figure out how to deconstruct elements of backgroundImages to (index, image).
I'm working to implement a Zig Zag game and following a set of instructions from an on-line course. I have a swift UIViewController, and I am trying now to use also SCNSceneRenderer (to do the game logic of keeping the game character on the zig-zag path). The code looks like this:
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController, SCNSceneRenderer{
let scene = SCNScene()
let cameraNode = SCNNode()
var person = SCNNode()
let firstBox = SCNNode()
var goingLeft = Bool()
var tempBox = SCNNode()
var boxNumber = Int()
var prevBoxNumber = Int()
override func viewDidLoad() {
print("Yes -- view did load")
self.createScene()
}
func renderer(render: SCNSceneRenderer, updateAtTime time: TimeInterval){
let deleteBox = self.scene.rootNode.childNode(withName: "\(prevBoxNumber)", recursively: true )
if (deleteBox?.position.x)! > (person.position.x + 1) || (deleteBox?.position.z)! > (person.position.z + 1) {
prevBoxNumber += 1
deleteBox?.removeFromParentNode()
createBox()
}
}
func createBox(){
tempBox = SCNNode(geometry: firstBox.geometry)
let prevBox = scene.rootNode.childNode(withName: "\(boxNumber)", recursively: true )
boxNumber += 1
tempBox.name = "\(boxNumber)"
let randomNumber = arc4random() % 2
switch randomNumber {
case 0:
tempBox.position = SCNVector3Make((prevBox?.position.x)! - firstBox.scale.x, (prevBox?.position.y)!, (prevBox?.position.z)!)
break
case 1:
tempBox.position = SCNVector3Make((prevBox?.position.x)! , (prevBox?.position.y)!, (prevBox?.position.z)! - firstBox.scale.z)
break
default:
break
}
self.scene.rootNode.addChildNode(tempBox)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if goingLeft == false {
person.removeAllActions()
person.runAction(SCNAction.repeatForever(SCNAction.move(by: SCNVector3Make(-100, 0, 0), duration: 20)))
goingLeft = true
} else {
person.removeAllActions()
person.runAction(SCNAction.repeatForever(SCNAction.move(by: SCNVector3Make(0, 0, -100), duration: 20)))
goingLeft = false
}
print("boxNumber is \(boxNumber)")
}
func createScene(){
boxNumber = 0
prevBoxNumber = 0
self.view.backgroundColor = UIColor.orange
let sceneView = self.view as! SCNView
sceneView.delegate = self
sceneView.scene = scene
//Create Person
let personGeo = SCNSphere(radius: 0.2)
person = SCNNode (geometry : personGeo)
let personMat = SCNMaterial()
personMat.diffuse.contents = UIColor.red
personGeo.materials = [personMat]
person.position = SCNVector3Make(0, 1.1, 0)
scene.rootNode.addChildNode(person)
//Create Camera
cameraNode.camera = SCNCamera()
cameraNode.camera?.usesOrthographicProjection = true
cameraNode.camera?.orthographicScale = 3
cameraNode.position = SCNVector3Make(20,20,20)
cameraNode.eulerAngles = SCNVector3Make(-45,45,0)
//let constraint = SCNLookAtConstraint(target: firstBox)
let constraint = SCNLookAtConstraint(target: person)
constraint.isGimbalLockEnabled = true
self.cameraNode.constraints = [constraint]
scene.rootNode.addChildNode(cameraNode)
person.addChildNode(cameraNode)
//Create Box
let firstBoxGeo = SCNBox(width: 1.0, height: 1.5, length: 1.0, chamferRadius: 0)
firstBox.geometry = firstBoxGeo
let boxMaterial = SCNMaterial()
boxMaterial.diffuse.contents = UIColor(red: 0.2, green: 0.8, blue: 0.9, alpha: 1.0)
firstBoxGeo.materials = [boxMaterial]
firstBox.position = SCNVector3Make(0,0,0)
scene.rootNode.addChildNode(firstBox)
firstBox.name = "\(boxNumber)"
for _ in 0...6{
createBox()
}
//Create light
let light = SCNNode()
light.light = SCNLight()
light.light?.type = SCNLight.LightType.directional
light.eulerAngles = SCNVector3Make(-45, 45, 0)
scene.rootNode.addChildNode(light)
//Create light2
let light2 = SCNNode()
light2.light = SCNLight()
light2.light?.type = SCNLight.LightType.directional
light2.eulerAngles = SCNVector3Make(45, 45, 0)
scene.rootNode.addChildNode(light2)
}
}
When I added SCNSceneRenderer I get the following error:
"Type 'GameViewController' cannot conform to protocol 'SCNSceneRenderer' because it has requirements that cannot be satisfied"
Since my GameViewController isn't recognized as a SCNSceneRenderer, I also get an error at this line:
sceneView.delegate = self
the error is "Cannot assign value of type 'GameViewController' to type 'SCNSceneRendererDelegate'
I'm new to swift programming, but this seems like I am trying to implement an interface like in Java, I've been looking at the Swift documentation but don't see what I need to do to make my class be functional as an SCNSceneRenderer. I would appreciate help to solve this problem. Thanks!
the app I'm working on is supposed to show a 3D object and the user can pick a color to color it. I have a SCNScene with multiple mesh creating a 3D model. I need to build a side interactive panel with colors the user can use to color the 3D model. The code is here on github.
I show you my code (for now on one class only, that's bad i know)
import UIKit
import QuartzCore
import SceneKit
import SpriteKit
class GameViewController: UIViewController {
var cameraOrbit = SCNNode()
let cameraNode = SCNNode()
let camera = SCNCamera()
let floorNode = SCNNode()
var wallNode = SCNNode()
var lateralWallRight = SCNNode()
var lateralWallLeft = SCNNode()
var spotLightNode = SCNNode()
//HANDLE PAN CAMERA
var initialPositionCamera = SCNVector3(x: -25, y: 70, z: 1450)
var translateEnabled = false
var lastXPos:Float = 0.0
var lastYPos:Float = 0.0
var xPos:Float = 0.0
var yPos:Float = 0.0
var lastWidthRatio: Float = 0
var lastHeightRatio: Float = 0.1
var widthRatio: Float = 0
var heightRatio: Float = 0.1
var fingersNeededToPan = 1 //change this from GUI
var panAttenuation: Float = 10 //5.0: very fast ---- 40.0 very slow
let maxWidthRatioRight: Float = 0.2
let maxWidthRatioLeft: Float = -0.2
let maxHeightRatioXDown: Float = 0.065
let maxHeightRatioXUp: Float = 0.4
//HANDLE PINCH CAMERA
var pinchAttenuation = 1.0 //1.0: very fast ---- 100.0 very slow
var lastFingersNumber = 0
let maxPinch = 146.0
let minPinch = 40.0
//OVERLAY
var colorPanelScene = SKScene()
var pickedColor: UIColor = UIColor.whiteColor()
var NodesToColors = [SKSpriteNode: UIColor]()
var didPickColor = false
var OverlayBackground: SKSpriteNode = SKSpriteNode()
func setColors() {
//Color Setup
let ColorWhite = colorPanelScene.childNodeWithName("ColorWhite") as! SKSpriteNode
let ColorRed = colorPanelScene.childNodeWithName("ColorRed") as! SKSpriteNode
let ColorBrown = colorPanelScene.childNodeWithName("ColorBrown")as! SKSpriteNode
let ColorDarkBrown = colorPanelScene.childNodeWithName("ColorDarkBrown")as! SKSpriteNode
let white = UIColor(red:1, green:0.95, blue:0.71, alpha:1)
let brown = UIColor(red:0.49, green:0.26, blue:0.17, alpha:1)
let red = UIColor(red:0.67, green:0.32, blue:0.21, alpha:1)
let darkBrown = UIColor(red:0.27, green:0.25, blue:0.21, alpha:1)
NodesToColors = [
ColorWhite: white,
ColorRed: red,
ColorBrown: brown,
ColorDarkBrown: darkBrown
]
OverlayBackground = colorPanelScene.childNodeWithName("OverlayBackground")as! SKSpriteNode
}
func blur(image image: UIImage) -> UIImage {
let radius: CGFloat = 20;
let context = CIContext(options: nil);
let inputImage = CIImage(CGImage: image.CGImage!);
let filter = CIFilter(name: "CIGaussianBlur");
filter?.setValue(inputImage, forKey: kCIInputImageKey);
filter?.setValue("\(radius)", forKey:kCIInputRadiusKey);
let result = filter?.valueForKey(kCIOutputImageKey) as! CIImage;
let rect = CGRectMake(radius * 2, radius * 2, image.size.width - radius * 4, image.size.height - radius * 4)
let cgImage = context.createCGImage(result, fromRect: rect);
let returnImage = UIImage(CGImage: cgImage);
return returnImage;
}
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene(named: "art.scnassets/Figure.scn")!
// MARK: Lights
//create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 1000, z: 1000)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
//MARK: Camera
camera.usesOrthographicProjection = true
camera.orthographicScale = 100
camera.zNear = 10
camera.zFar = 3000
cameraNode.position = initialPositionCamera
cameraNode.camera = camera
cameraOrbit = SCNNode()
cameraOrbit.addChildNode(cameraNode)
scene.rootNode.addChildNode(cameraOrbit)
//initial camera setup
self.cameraOrbit.eulerAngles.y = Float(-2 * M_PI) * lastWidthRatio
self.cameraOrbit.eulerAngles.x = Float(-M_PI) * lastHeightRatio
lastXPos = self.cameraNode.position.x
lastYPos = self.cameraNode.position.y
//MARK: Floor
let floor = SCNFloor()
floor.reflectionFalloffEnd = 0
floor.reflectivity = 0
floorNode.geometry = floor
floorNode.name = "Floor"
floorNode.geometry!.firstMaterial!.diffuse.contents = "art.scnassets/floor.png"
floorNode.geometry!.firstMaterial!.locksAmbientWithDiffuse = true
floorNode.geometry!.firstMaterial!.diffuse.wrapS = SCNWrapMode.Repeat
floorNode.geometry!.firstMaterial!.diffuse.wrapT = SCNWrapMode.Repeat
floorNode.geometry!.firstMaterial!.diffuse.mipFilter = SCNFilterMode.Nearest
floorNode.geometry!.firstMaterial!.doubleSided = false
floorNode.castsShadow = true
scene.rootNode.addChildNode(floorNode)
//MARK: Walls
// create the wall geometry
let wallGeometry = SCNPlane.init(width: 500.0, height: 300.0)
wallGeometry.firstMaterial!.diffuse.contents = "art.scnassets/background.jpg"
wallGeometry.firstMaterial!.diffuse.mipFilter = SCNFilterMode.Nearest
wallGeometry.firstMaterial!.diffuse.wrapS = SCNWrapMode.Repeat
wallGeometry.firstMaterial!.diffuse.wrapT = SCNWrapMode.Repeat
wallGeometry.firstMaterial!.doubleSided = false
wallGeometry.firstMaterial!.locksAmbientWithDiffuse = true
wallNode = SCNNode.init(geometry: wallGeometry)
wallNode.name = "FrontWall"
wallNode.position = SCNVector3Make(0, 120, -300) //this moves all 3 walls
wallNode.castsShadow = true
// RIGHT LATERAL WALL
lateralWallRight = SCNNode.init(geometry: wallGeometry)
lateralWallRight.name = "lateralWallRight"
lateralWallRight.position = SCNVector3Make(-300, -20, 150);
lateralWallRight.rotation = SCNVector4(x: 0, y: 1, z: 0, w: Float(M_PI/3))
lateralWallRight.castsShadow = true
wallNode.addChildNode(lateralWallRight)
// LEFT LATERAL WALL
lateralWallLeft = SCNNode.init(geometry: wallGeometry)
lateralWallLeft.name = "lateralWallLeft"
lateralWallLeft.position = SCNVector3Make(300, -20, 150);
lateralWallLeft.rotation = SCNVector4(x: 0, y: -1, z: 0, w: Float(M_PI/3))
lateralWallLeft.castsShadow = true
wallNode.addChildNode(lateralWallLeft)
//front walls
scene.rootNode.addChildNode(wallNode)
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = false //not needed
// configure the view
scnView.backgroundColor = UIColor.grayColor()
//MARK: Gesture Recognizer in SceneView
// add a pan gesture recognizer
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.handlePan(_:)))
scnView.addGestureRecognizer(panGesture)
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(GameViewController.handleTap(_:)))
scnView.addGestureRecognizer(tapGesture)
// add a pinch gesture recognizer
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(GameViewController.handlePinch(_:)))
scnView.addGestureRecognizer(pinchGesture)
//MARK: OverLay
colorPanelScene = SKScene(fileNamed: "art.scnassets/ColorPanelScene")!
scnView.overlaySKScene = colorPanelScene
scnView.overlaySKScene!.userInteractionEnabled = true;
didPickColor = false
setColors()
//let OverlayBackground = colorPanelScene.childNodeWithName("OverlayBackground")as! SKSpriteNode
}
func handlePan(gestureRecognize: UIPanGestureRecognizer) {
let numberOfTouches = gestureRecognize.numberOfTouches()
let translation = gestureRecognize.translationInView(gestureRecognize.view!)
if (numberOfTouches==fingersNeededToPan) {
widthRatio = Float(translation.x) / Float(gestureRecognize.view!.frame.size.width) + lastWidthRatio
heightRatio = Float(translation.y) / Float(gestureRecognize.view!.frame.size.height) + lastHeightRatio
// HEIGHT constraints
if (heightRatio >= maxHeightRatioXUp ) {
heightRatio = maxHeightRatioXUp
}
if (heightRatio <= maxHeightRatioXDown ) {
heightRatio = maxHeightRatioXDown
}
// WIDTH constraints
if(widthRatio >= maxWidthRatioRight) {
widthRatio = maxWidthRatioRight
}
if(widthRatio <= maxWidthRatioLeft) {
widthRatio = maxWidthRatioLeft
}
self.cameraOrbit.eulerAngles.y = Float(-2 * M_PI) * widthRatio
self.cameraOrbit.eulerAngles.x = Float(-M_PI) * heightRatio
lastFingersNumber = fingersNeededToPan
//TRANSLATION pan
} else if numberOfTouches == (fingersNeededToPan+1) {
if translateEnabled {
xPos = (lastXPos + Float(-translation.x))/(panAttenuation)
yPos = (lastYPos + Float(translation.y))/(panAttenuation)
self.cameraNode.position.x = xPos
self.cameraNode.position.y = yPos
}
lastFingersNumber = fingersNeededToPan+1
}
if (lastFingersNumber == fingersNeededToPan && numberOfTouches != fingersNeededToPan) {
lastWidthRatio = widthRatio
lastHeightRatio = heightRatio
}
if lastFingersNumber != (fingersNeededToPan+1) && numberOfTouches != (fingersNeededToPan+1) {
lastXPos = xPos
lastYPos = yPos
}
if (gestureRecognize.state == .Ended) {
if (lastFingersNumber==fingersNeededToPan) {
lastWidthRatio = widthRatio
lastHeightRatio = heightRatio
//print("lastHeight: \(round(lastHeightRatio*100))")
//print("lastWidth: \(round(lastWidthRatio*100))")
}
if lastFingersNumber==(fingersNeededToPan+1) {
lastXPos = xPos
lastYPos = yPos
print("lastX: \(xPos)")
print("lastY: \(yPos)")
}
print("Pan with \(lastFingersNumber) finger\(lastFingersNumber>1 ? "s" : "")")
}
}
func handlePinch(gestureRecognize: UIPinchGestureRecognizer) {
let pinchVelocity = Double.init(gestureRecognize.velocity)
//print("PinchVelocity \(pinchVelocity)")
camera.orthographicScale -= (pinchVelocity/pinchAttenuation)
if camera.orthographicScale <= minPinch {
camera.orthographicScale = minPinch
}
if camera.orthographicScale >= maxPinch {
camera.orthographicScale = maxPinch
}
if (gestureRecognize.state == .Ended) {
print("\nPinch: \(round(camera.orthographicScale))\n")
}
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
print("---------------TAP-----------------")
// retrieve the SCNView
let scnView = self.view as! SCNView
let touchedPointInScene = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(touchedPointInScene, options: nil)
let OverlayView = colorPanelScene.view! as SKView
let touchedPointInOverlay = gestureRecognize.locationInView(OverlayView)
// if button color are touched
if OverlayBackground.containsPoint(touchedPointInOverlay) {
print("OVERLAY: tap in \(touchedPointInOverlay)")
for (node, color) in NodesToColors {
// Check if the location of the touch is within the button's bounds
if node.containsPoint(touchedPointInOverlay) {
print("\(node.name!) -> color picked \(color.description)")
pickedColor = color
didPickColor = true
}
}
} else {//if figure is touched
// check that we clicked on at least one object
if hitResults.count > 0 && didPickColor {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
print("OBJECT tap: \(result.node.name!)")
//Exclude floor and wall from color
if result.node! != floorNode && result.node! != wallNode && result.node! != lateralWallRight && result.node! != lateralWallLeft {
// get its material
let material = result.node!.geometry!.firstMaterial!
print("material: \(material.name!)")
// begin coloration
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - keep color
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.3)
material.diffuse.contents = self.pickedColor
SCNTransaction.commit()
}
SCNTransaction.commit()
material.diffuse.contents = pickedColor
}
}
}
print("-----------------------------------\n")
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Landscape
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
The code starts with a setColor function that catch images from ColorPanelScene.sks (this SKScene has a strange y-axis movement, i don't know why).
func setColors() {
//Color Setup
let ColorWhite = colorPanelScene.childNodeWithName("ColorWhite") as! SKSpriteNode
let ColorRed = colorPanelScene.childNodeWithName("ColorRed") as! SKSpriteNode
let ColorBrown = colorPanelScene.childNodeWithName("ColorBrown")as! SKSpriteNode
let ColorDarkBrown = colorPanelScene.childNodeWithName("ColorDarkBrown")as! SKSpriteNode
let white = UIColor(red:1, green:0.95, blue:0.71, alpha:1)
let brown = UIColor(red:0.49, green:0.26, blue:0.17, alpha:1)
let red = UIColor(red:0.67, green:0.32, blue:0.21, alpha:1)
let darkBrown = UIColor(red:0.27, green:0.25, blue:0.21, alpha:1)
NodesToColors = [
ColorWhite: white,
ColorRed: red,
ColorBrown: brown,
ColorDarkBrown: darkBrown
]
OverlayBackground = colorPanelScene.childNodeWithName("OverlayBackground")as! SKSpriteNode
}
Then, you can see a blur effect function that I would like to add to the panel background. Do you know how to do it to a SKNode? That would be easy if I use UIView instead, but i don't know how to back layer Views.
func blur(image image: UIImage) -> UIImage {
let radius: CGFloat = 20;
let context = CIContext(options: nil);
let inputImage = CIImage(CGImage: image.CGImage!);
let filter = CIFilter(name: "CIGaussianBlur");
filter?.setValue(inputImage, forKey: kCIInputImageKey);
filter?.setValue("\(radius)", forKey:kCIInputRadiusKey);
let result = filter?.valueForKey(kCIOutputImageKey) as! CIImage;
let rect = CGRectMake(radius * 2, radius * 2, image.size.width - radius * 4, image.size.height - radius * 4)
let cgImage = context.createCGImage(result, fromRect: rect);
let returnImage = UIImage(CGImage: cgImage);
return returnImage;
}
If you look at the buttons on ColorPanelScene.sks they have wrong names because I used a workaround to make that panel works. It seems to match color nodes, textures and nodes names in a inverse way.
That's obviously a bad implementation of a side panel. Please, can you help me to build a better interactive panel? Thank You.
Here is the code:
import SpriteKit
import CoreMotion
struct PhysicsCatagory {
static let Player :UInt32 = 0x1 << 0
static let shark :UInt32 = 0x1 << 1
static let jellyfish :UInt32 = 0x1 << 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var Player = SKSpriteNode()
var game = true
var playerPos = false
var ScoreCount = 0
let myLabel = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
var HighScore = 0
let DisplayScore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
let LeaderBoardScore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
let LeaderBoardHighscore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
var CheckGameState = false
let playButton = SKSpriteNode(imageNamed: "Play")
let Scores = SKSpriteNode(imageNamed: "LeaderBoard")
var PlayerUpState = false
var PlayerDownState = false
var ifPlayerDrawJustCalled = false
var TextureAtlas = SKTextureAtlas()
var TextureArray = [SKTexture]()
var TextureAtlas2 = SKTextureAtlas()
var TextureArray2 = [SKTexture]()
var TextureAtlas3 = SKTextureAtlas()
var TextureArray3 = [SKTexture]()
var motionManager: CMMotionManager!
var fishYpos = 115.0
let shark = SKSpriteNode(imageNamed: "shark")
let jellyfish = SKSpriteNode(imageNamed: "jellyfish")
override func didMoveToView(view: SKView) {
print("called")
motionManager = CMMotionManager()
motionManager.startGyroUpdates()
motionManager.gyroUpdateInterval = 0.02
backgroundColor = UIColor(red: 0.0, green: 7.0, blue: 1.0, alpha: 1.0)
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
if(HighscoreDefault.valueForKey("Highscore") != nil){
HighScore = HighscoreDefault.valueForKey("Highscore") as! Int
}
TextureAtlas = SKTextureAtlas(named: "Images")
TextureArray.append(SKTexture(imageNamed: "win_1.png"))
TextureArray.append(SKTexture(imageNamed: "win_2.png"))
TextureArray.append(SKTexture(imageNamed: "win_3.png"))
TextureArray.append(SKTexture(imageNamed: "win_4.png"))
TextureAtlas3 = SKTextureAtlas(named: "Images")
TextureArray3.append(SKTexture(imageNamed: "jellyfish_1.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_2.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_3.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_4.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_5.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_6.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_7.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_8.png"))
TextureAtlas2 = SKTextureAtlas(named: "Images")
TextureArray2.append(SKTexture(imageNamed: "shark_1.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_2.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_3.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_4.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_5.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_6.png"))
Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0])
self.physicsWorld.contactDelegate = self
Player.zPosition = 10.0
Player.position = CGPoint(x: 80, y: fishYpos)
Player.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 30, height: 30))
Player.physicsBody?.dynamic = false
Player.physicsBody?.affectedByGravity = false
myLabel.text = "\(ScoreCount)"
myLabel.fontSize = 70
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), frame.size.height-150)
myLabel.zPosition = 18.0
addChild(myLabel)
addChild(Player)
Player.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray, timePerFrame: 0.20)))
var BubbleTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self,selector: "addBubble", userInfo: nil, repeats: true)
var Gyro = NSTimer.scheduledTimerWithTimeInterval(0.02, target:self,selector: "gyroFunction", userInfo: nil, repeats: true)
var MainTimer1 = NSTimer.scheduledTimerWithTimeInterval(1, target:self,selector: "RunTimeTimer", userInfo: nil, repeats: true)
var sharkTimer = NSTimer.scheduledTimerWithTimeInterval(0.70, target: self, selector: "RunSharkTimer", userInfo: nil, repeats: true)
var jellyfishTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "RunJellyfishTimer", userInfo: nil, repeats: true)
}
func addBubble(){
let randomNum1 = Int(arc4random_uniform(3))
if(randomNum1 == 2){
let randomNum2 = Int(arc4random_uniform(2))
if(randomNum2 == 1){
let Bubble1 = SKSpriteNode(imageNamed: "Bubble1")
Bubble1.position.x = Player.position.x+9
Bubble1.position.y = Player.position.y
Bubble1.zPosition = 2.0
addChild(Bubble1)
Bubble1.runAction(SKAction.moveToY( frame.size.height+20, duration: 3.0))
}
if(randomNum2 == 0){
let Bubble2 = SKSpriteNode(imageNamed: "Bubble2")
Bubble2.position.x = Player.position.x+9
Bubble2.position.y = Player.position.y
Bubble2.zPosition = 3.0
addChild(Bubble2)
Bubble2.runAction(SKAction.moveToY( frame.size.height+20, duration: 3.0))
}
}
}
func RunTimeTimer(){
if(game == true){
timer()
}
}
func RunSharkTimer(){
if(game == true){
addShark()
}
}
func RunJellyfishTimer(){
if(game == true){
addJellyfish()
}
}
func gyroFunction(){
if let gyro_y = motionManager.gyroData?.rotationRate.y {
if(fishYpos+gyro_y*(-10) > 115){
if(CGFloat(fishYpos+gyro_y*(-10)) < frame.size.height-115){
fishYpos = fishYpos+gyro_y*(-10)
let fishAction = SKAction.moveToY(CGFloat(fishYpos), duration: 0.05)
Player.runAction(fishAction)
}
}
}
}
func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA as! SKSpriteNode
let secondBody = contact.bodyB as! SKSpriteNode
if(((firstBody.name == "Player") && (secondBody.name == "shark")) || (firstBody.name == "shark") && (secondBody.name == "Player") || ((firstBody.name == "Player") && (secondBody.name == "jellyfish")) || (firstBody.name == "jellyfish") && (secondBody.name == "Player")){
game = false
if(CheckGameState == false){
playButton.xScale = 1.9
playButton.yScale = 1.9
playButton.zPosition = 12.0
playButton.position = CGPoint(x: frame.midX-50, y: frame.midY-140)
playButton.name = "playButton"
playButton.userInteractionEnabled = false
addChild(playButton)
if(ScoreCount>HighScore){
HighScore = ScoreCount
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setInteger(HighScore, forKey: "Highscore")
}
LeaderBoardScore.text = "\(ScoreCount)"
LeaderBoardHighscore.text = "\(HighScore)"
LeaderBoardHighscore.position = CGPoint(x: frame.midX+30 , y: frame.midY+5)
LeaderBoardHighscore.xScale = 2.0
LeaderBoardHighscore.yScale = 2.0
LeaderBoardHighscore.zPosition = 15.0
LeaderBoardHighscore.fontColor = UIColor.purpleColor()
LeaderBoardScore.position = CGPoint(x: frame.midX+60 , y: frame.midY+72)
LeaderBoardScore.fontColor = UIColor.purpleColor()
LeaderBoardScore.xScale = 2.0
LeaderBoardScore.zPosition = 15.0
LeaderBoardScore.yScale = 2.0
addChild(LeaderBoardHighscore)
addChild(LeaderBoardScore)
Scores.xScale = 2
Scores.yScale = 2
Scores.zPosition = 11.0
Scores.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(Scores)
CheckGameState = true
}
}
}
func addShark(){
Player.physicsBody?.collisionBitMask = PhysicsCatagory.shark
Player.physicsBody?.contactTestBitMask = PhysicsCatagory.shark
Player.name = "Player"
Player.physicsBody?.dynamic = true
Player.physicsBody?.affectedByGravity = false
let randomNumShark = arc4random_uniform(2)
if(randomNumShark == 1){
let shark = SKSpriteNode(imageNamed: "shark_1.png")
shark.position.x = frame.size.width
let PositionY = arc4random_uniform(UInt32(frame.size.height))
shark.position.y = CGFloat(PositionY)
addChild(shark)
let sharkGoForward = SKAction.moveToX(CGFloat(-1100), duration: 1.5)
shark.runAction(sharkGoForward)
shark.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: shark.size.width, height:shark.size.height))
shark.physicsBody?.categoryBitMask = PhysicsCatagory.Player
shark.physicsBody?.contactTestBitMask = PhysicsCatagory.Player
shark.physicsBody?.collisionBitMask = PhysicsCatagory.Player
shark.physicsBody?.dynamic = true
shark.physicsBody?.affectedByGravity = false
shark.name = "shark"
shark.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray2, timePerFrame: 0.05)))
}
}
func addJellyfish(){
Player.physicsBody?.collisionBitMask = PhysicsCatagory.jellyfish
Player.physicsBody?.contactTestBitMask = PhysicsCatagory.jellyfish
Player.name = "Player"
Player.physicsBody?.dynamic = true
Player.physicsBody?.affectedByGravity = false
let randomNumJelly = arc4random_uniform(2)
if(randomNumJelly == 1){
let jellyfish = SKSpriteNode(imageNamed: "jellyfish")
jellyfish.position.y = 0
let PositionX = arc4random_uniform(UInt32(frame.size.width))
jellyfish.position.x = CGFloat(PositionX)
addChild(jellyfish)
let jellyfishGoUp = SKAction.moveToY(CGFloat(frame.size.height+100), duration: 2.0)
jellyfish.runAction(jellyfishGoUp)
jellyfish.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: jellyfish.size.width, height:jellyfish.size.height))
jellyfish.physicsBody?.categoryBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.contactTestBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.collisionBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.dynamic = true
jellyfish.physicsBody?.affectedByGravity = false
jellyfish.name = "jellyfish"
jellyfish.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray3, timePerFrame: 0.05)))
}
}
func timer(){
if(game == true){
ScoreCount++
myLabel.text = "\(ScoreCount)"
}
}
func rePositionPlayer(){
Player.removeFromParent()
Player.position = CGPoint(x: 80, y: 220)
addChild(Player)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in (touches ) {
let location = touch.locationInNode(self)
if(game == false){
if playButton.containsPoint(location){
game = true
LeaderBoardHighscore.removeFromParent()
LeaderBoardScore.removeFromParent()
playButton.removeFromParent()
Scores.removeFromParent()
CheckGameState = false
rePositionPlayer()
ScoreCount = 0
fishYpos = 220
}
}
if(game == true){
}
}
}
override func update(currentTime: CFTimeInterval) {
}
}
My error is at the line
let secondbody = contact.bodyB as! SKSpriteNode
It says
can cast SKPhysicsBody to unrealted SKSpriteNode
How to fix this issue?
Try saying let secondbody.node = contact.bodyB as! SKSpriteNode
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.