Swift Ios 8 MKPolylineRenderer to trace location - xcode

Hi so i am having trouble with trying to create this MKPolyline for my ios 8 app. This is suppose to trace the users's location and draw a line where ever it goes. I have been looking at tutorials online and they are using ios 7 or 6. Any help would be great. Thank in advance .
import UIKit
import MapKit
import CoreLocation
class SecondViewController: UIViewController , CLLocationManagerDelegate , MKMapViewDelegate{
#IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
var currentLocation = CLLocation()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude , locationManager.location.coordinate.longitude)
var objectAnnotation = MKPointAnnotation()
objectAnnotation.coordinate = pinLocation
objectAnnotation.title = "Current Location"
self.map.addAnnotation(objectAnnotation)
}
func addPolyLineToMap(locations: [CLLocation!])
{
var coordinates = locations.map({ (location: CLLocation!) -> CLLocationCoordinate2D in
return location.coordinate
})
var geodesic = MKGeodesicPolyline(coordinates: &coordinates[0], count: 2)
map.addOverlay(geodesic , level: MKOverlayLevel.AboveRoads )
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 4
return polylineRenderer
}
return nil
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
println("Error: " + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
//centering location
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
var latDelta:CLLocationDegrees = 0.01
var longDelta:CLLocationDegrees = 0.01
var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
`var pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude , location.coordinate.longitude)
map.setRegion(region, animated: true)
addPolyLineToMap(location)
}
}

Related

Looping Videos with XCode ARKit Image Tracking

Hello I'm new into developing and right now I'm working on an AR application which works with image tracking and it should play different videos on different tracked images.
Right now the video stops, how can I loop the video?
Also if the image is not in the camera view, the video continues. Is there a pause function too?
I would be thankful for every hints.
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
#IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARImageTrackingConfiguration()
if let trackedImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: Bundle.main) {
configuration.trackingImages = trackedImages
configuration.maximumNumberOfTrackedImages = 2
}
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
if let imageAnchor = anchor as? ARImageAnchor {
let size = imageAnchor.referenceImage.physicalSize
var videoNode = SKVideoNode()
switch imageAnchor.name {
case "Image1":
videoNode = SKVideoNode(fileNamed: "Image1.mp4")
case "Image2":
videoNode = SKVideoNode(fileNamed: "Image2.mp4")
case "Image3":
videoNode = SKVideoNode(fileNamed: "Image3.mp4")
default:
break
}
videoNode.play()
let videoScene = SKScene(size: CGSize(width: 1280, height: 960))
videoScene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
videoScene.addChild(videoNode)
let plane = SCNPlane(width: size.width, height: size.height)
plane.firstMaterial?.diffuse.contents = videoScene
let planeNode = SCNNode(geometry: plane)
plane.firstMaterial?.isDoubleSided = true
planeNode.eulerAngles.x = .pi / 2
node.addChildNode(planeNode)
return node
}
return nil
}
}

How to Added objects in SceneKit SWIFT

I have 2 files that I imported from Blender(3D design program) they are both .dae specifically they are "CampusField1.dae" CampusField is the ground/floor of the game and "Bob.dae" is the Man/character. My question is when I set CampusField1 as the scene how do I get "Bob" in the scene too. And the other question is lets say I export the .dae from blender now I put the file in the game... every things good but then is the animation for Bob already attached to the Bob.dae file or do I have to export something else from blender so that I can run the animation because I don't know what the animation ID would be or how to actually make it run and to actually make Bob do something.
Code:
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = SCNScene(named: "art.scnassets/CampusField1.dae")!
let src = SCNSceneSource(URL: yourSceneURL, options: nil)
let node = src.entryWithIdentifier("Bob", withClass: SCNNode.self) as SCNNode
let animation = node.entryWithIdentifier("yourAnimationID", withClass: CAAnimation.self) as CAAnimation
Full GameController Below!:
import UIKit
import QuartzCore
import SceneKit
//============================================================
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//-------------------------
let scene = SCNScene(named: "art.scnassets/CampusField1.dae")!
let src = SCNSceneSource(URL: yourSceneURL, options: nil)
let node = src.entryWithIdentifier("Bob", withClass: SCNNode.self) as SCNNode
let animation = node.entryWithIdentifier("yourAnimationID", withClass: CAAnimation.self) as CAAnimation
//--------------------------
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
//-----------------------------------------------
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
//-----------------------------------------------
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
//----------------------------------------------
//_ = scene.rootNode.childNodeWithName("Bob", recursively: true)!
// _ = scene.rootNode.childNodeWithName("CampusField1", recursively: true)!
//--------------------------------------------------------
// Bob.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1)))
let scnView = self.view as! SCNView
scnView.scene = scene
scnView.allowsCameraControl = true
scnView.showsStatistics = false
scnView.backgroundColor = UIColor.whiteColor()
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
scnView.addGestureRecognizer(tapGesture)
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
let scnView = self.view as! SCNView
let p = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(p, options: nil)
if hitResults.count > 0 {
let result: AnyObject! = hitResults[0]
let material = result.node!.geometry!.firstMaterial!
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material.emission.contents = UIColor.yellowColor()
SCNTransaction.commit()
}
}
//==================================================
override func shouldAutorotate() -> Bool {
return true
}
//============================
override func prefersStatusBarHidden() -> Bool {
return true
}
//==========================
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
//=============================
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
The first thing to tell you is you have got two SCNScene; CampusField and Bob. Therefore you need to take out the character node from the Bob scene.
You need to name the node as like from the above figure. And extract that node from the scene as:
let bobScene = SCNScene(named: "Bob.dae")
let bobNode = personScene?.rootNode.childNodeWithName("person", recursively: true)
let campusFieldScene = SCNScene(named: "CampusField1.dae")
campusFieldScene.rootNode.addChildNode(bobNode)

How do I clear pins on a mapview in swift?

Part of my app contains a mapview which searches automatically based on a keyword. I added a textbox and search button to my mapview, but I noticed the pins do not clear from the previous search. How do I clear the map of all pins before the new search?
import UIKit
import MapKit
import CoreLocation
import iAd
class MapClass: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate, ADBannerViewDelegate {
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var holidayKeyWord = NSString()
#IBOutlet var mapSearchTextbox: UITextField!
#IBOutlet weak var mapView: MKMapView!
#IBOutlet var adBannerView: ADBannerView!
var locationManager: CLLocationManager!
let searchRadius: CLLocationDistance = 2000
override func viewDidLoad() {
super.viewDidLoad()
holidayKeyWord = "Restaurant"
println(holidayKeyWord)
mapSearchTextbox.text = holidayKeyWord as String
self.canDisplayBannerAds = true
self.adBannerView?.delegate = self
self.adBannerView?.hidden = false
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
#IBAction func mapSearchButton(sender: UIButton) {
//clear pins
var holidayKeyWord = mapSearchTextbox.text
if (CLLocationManager.locationServicesEnabled())
{
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = holidayKeyWord as String
let search = MKLocalSearch(request: request)
search.startWithCompletionHandler {
(response: MKLocalSearchResponse!, error: NSError!) in
for item in response.mapItems as! [MKMapItem] {
println(item.name)
self.addPinToMapView(item.name, latitude: item.placemark.location.coordinate.latitude, longitude: item.placemark.location.coordinate.longitude)
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//replace spaces with dashes in wikiDate string
if (segue.identifier == "amazonToWeb") {
var wikiDate = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Ddigital-text&field-keywords=\(holidayKeyWord)"
var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
DestViewController.wikiDate = wikiDate
}
if (segue.identifier == "searchToWeb") {
var wikiDate = "http://www.bing.com"
var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
DestViewController.wikiDate = wikiDate
}
if (segue.identifier == "ebayToWeb") {
var wikiDate = "http://search.ebay.com/\(holidayKeyWord)"
var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
DestViewController.wikiDate = wikiDate
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
var latitude: Double = location.coordinate.latitude
var longitude: Double = location.coordinate.longitude
let initialLocation = CLLocation(latitude: latitude, longitude: longitude)
// 1
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = holidayKeyWord as String
// 2
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
request.region = MKCoordinateRegion(center: initialLocation.coordinate, span: span)
// 3
let search = MKLocalSearch(request: request)
search.startWithCompletionHandler {
(response: MKLocalSearchResponse!, error: NSError!) in
for item in response.mapItems as! [MKMapItem] {
println(item.name)
//println("Latitude = \(item.placemark.location.coordinate.latitude)")
//println("Longitude = \(item.placemark.location.coordinate.longitude)")
self.addPinToMapView(item.name, latitude: item.placemark.location.coordinate.latitude, longitude: item.placemark.location.coordinate.longitude)
}
}
locationManager.stopUpdatingLocation()
let coordinateRegion = MKCoordinateRegionMakeWithDistance(initialLocation.coordinate, searchRadius * 2.0, searchRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func addPinToMapView(title: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let annotation = MyAnnotation(coordinate: location, title: title)
mapView.addAnnotation(annotation)
}
func removePinFromMapView(title: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let annotation = MyAnnotation(coordinate: location, title: title)
mapView.removeAnnotation(annotation)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
println("Error: " + error.localizedDescription)
}
Iterate through your annotations and delete them one by one like this:
if let annotations = self.mapView.annotations {
for _annotation in annotations {
if let annotation = _annotation as? MKAnnotation
{
self.mapView.removeAnnotation(annotation)
}
}
}
There is a short way of doing #ezcoding's answer.
mapView.removeAnnotations(mapView.annotations)
You are adding the pins by saying addAnnotation. To remove them, just reverse that: say removeAnnotation.
[self.mapView removeAnnotations:mapView.annotations];
For Swift 3.0
func removeAllAnnotations() {
for annotation in self.mapView.annotations {
self.mapView.removeAnnotation(annotation)
}
}

Can't change marker icon in MapKit

I did everything on the answer of this link:
Swift different images for Annotation
But the marker icon won't change it just stays the same I tried every way I could find on google but they all give the same result.
This is my code:
import UIKit
import MapKit
class Kaart: UIViewController, MKMapViewDelegate{
#IBOutlet weak var mapView: MKMapView!
let initialLocation = CLLocation(latitude: 52.20614380, longitude: 21.04759094)
let markerLocation = CLLocationCoordinate2D(latitude: 52.20614380, longitude: 21.04759094)
override func viewDidLoad() {
super.viewDidLoad()
UINavigationBar.appearance().translucent = false;
UINavigationBar.appearance().barTintColor = UIColor(red: CGFloat(193.0/255.0), green: 58/255, blue: 44/255, alpha: 1)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
//Set Default location
centerMapOnLocation(initialLocation)
//Place markers
var info1 = CustomPointAnnotation()
info1.coordinate = CLLocationCoordinate2DMake(42, -84)
info1.title = "Info1"
info1.subtitle = "Subtitle"
info1.imageName = "vlag.png"
mapView.addAnnotation(info1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 50.0, regionRadius * 50.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
let cpa = annotation as! CustomPointAnnotation
anView.image = UIImage(named:cpa.imageName)
return anView
}
}
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String!
}

Node not moving after changing scenes

I made a (basic) game, works perfect, goes to GameOverScene, and when it comes back from GameOverScene to GameScene, the player(spritenode) is not moving anymore..
I commented in the GameScene code which functions its about
I get no error from Xcode!
the bug is in the gamescene.swift file(functions: swipedRight + swipedLeft + swipedUp + swipedDown):
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var kikker:SKSpriteNode = SKSpriteNode()
var auto1:SKSpriteNode = SKSpriteNode()
var lastYieldTimeInterval:NSTimeInterval = NSTimeInterval()
var lastUpdateTimerInterval:NSTimeInterval = NSTimeInterval()
let playerCategory:UInt32 = 0x1 << 1
let auto1Category:UInt32 = 0x1 << 0
required init(coder aDecoder:NSCoder) {
fatalError("NSCoder not supported")
}
override init(size:CGSize) {
super.init(size:size)
anchorPoint = CGPoint(x:0, y:1.0)
let background = SKSpriteNode(imageNamed: "bg5")
var auto1:SKSpriteNode = SKSpriteNode(imageNamed: "auto1")
background.position = CGPoint(x:0, y:0)
background.anchorPoint=CGPoint(x:0,y:1.0)
addChild(background)
kikker = SKSpriteNode(imageNamed:"kikker5")
kikker.anchorPoint = CGPoint(x:0.5, y:0.5)
kikker.xScale = 0.22
kikker.yScale = 0.22
self.physicsWorld.gravity = CGVectorMake(0,0)
self.physicsWorld.contactDelegate = self
kikker.physicsBody?.categoryBitMask = playerCategory
kikker.physicsBody?.contactTestBitMask = auto1Category
kikker.physicsBody?.collisionBitMask = 0
kikker.physicsBody?.usesPreciseCollisionDetection = true
kikker.physicsBody = SKPhysicsBody(circleOfRadius: kikker.size.width/2)
kikker.physicsBody?.dynamic = false
kikker.position = CGPointMake(self.frame.size.width/2, -610)
addChild(kikker)
println(kikker.position)
}
func didBeginContact(contact: SKPhysicsContact!) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
if(contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
firstBody = contact.bodyA
secondBody = contact.bodyB
}else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if((firstBody.categoryBitMask & auto1Category) != 0 && (secondBody.categoryBitMask & playerCategory) != 0)
{
println("aasda")
aangereden(contact.bodyB.node as SKSpriteNode, player: contact.bodyA.node as SKSpriteNode)
}
}
func addCar(){
var auto1:SKSpriteNode = SKSpriteNode(imageNamed: "auto2")
auto1.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(auto1.size.width/2, auto1.size.height/2) )
auto1.physicsBody?.dynamic = true
auto1.physicsBody?.categoryBitMask = auto1Category
auto1.physicsBody?.contactTestBitMask = playerCategory
auto1.physicsBody?.collisionBitMask = 0
auto1.physicsBody?.usesPreciseCollisionDetection = true
let position : CGFloat = 51 + (CGFloat(arc4random_uniform(4)+2)*(-111))
auto1.anchorPoint = CGPoint(x:0.5, y:0.5)
auto1.position = CGPointMake(-auto1.size.width/2, position)
self.addChild(auto1)
let minDuration = 2.5
let maxDuration = 4.0
let rangeDuration = maxDuration - minDuration
let duration = Int(arc4random()) % Int(rangeDuration) + Int(minDuration)
var actionArray:NSMutableArray = NSMutableArray()
actionArray.addObject(SKAction.moveTo(CGPointMake(375 + auto1.size.width/2, position), duration: NSTimeInterval(duration)))
actionArray.addObject(SKAction.removeFromParent())
auto1.runAction(SKAction.sequence(actionArray))
}
println("DOOD")
player.removeFromParent()
}
func updateWithTimeSinceLastUpdate(timeSinceLastUpdate:CFTimeInterval){
lastYieldTimeInterval += timeSinceLastUpdate
if (lastYieldTimeInterval > 2.5){
lastYieldTimeInterval = 0
addCar()
}
}
//#1 function not working after changing scenes: the function is executing, the println works
but for some reason the runAction doesnt do its job, the node(kikker) is not moving as it should
func swipedRight1(sender:UISwipeGestureRecognizer){
var naarRechts = SKAction()
var positionX = kikker.position.x
println("right2")
if(kikker.position.x<200){
println(positionX)
positionX = kikker.position.x + 125
println(positionX)
naarRechts = SKAction.moveToX(positionX , duration: 0.25)
kikker.zRotation=(-1.570)
kikker.runAction(naarRechts)
}
}
//#2 function not working, same story
func swipedLeft1(sender:UISwipeGestureRecognizer){
var naarLinks = SKAction()
var positionX = kikker.position.x
if(kikker.position.x>150){
positionX = kikker.position.x - 125
naarLinks = SKAction.moveToX(positionX , duration: 0.25)
kikker.zRotation=(1.570)
kikker.runAction(naarLinks)
}
}
//#3 function not working, same story
func swipedDown1(sender:UISwipeGestureRecognizer){
var naarBeneden = SKAction()
var positionY = kikker.position.y
if(kikker.position.y>(-600)){
positionY = kikker.position.y - 111
naarBeneden = SKAction.moveToY(positionY , duration: 0.25)
kikker.zRotation=3.141
kikker.runAction(naarBeneden)
}
}
//#4 function not working, same story
func swipedUp1(sender:UISwipeGestureRecognizer){
var naarBoven = SKAction()
var positionY = kikker.position.y
if(kikker.position.y < (-60)){
positionY = kikker.position.y + 111
naarBoven = SKAction.moveToY(positionY, duration: 0.25)
kikker.zRotation=0
kikker.runAction(naarBoven)
}
if(positionY > (-60)){
var gameOverScene:SKScene = GameOverScene(size: self.size)
self.view?.presentScene(gameOverScene)
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
var timeSinceLastUpdate = currentTime - lastUpdateTimerInterval
lastUpdateTimerInterval = currentTime
if (timeSinceLastUpdate > 1){
timeSinceLastUpdate = 1/60
lastUpdateTimerInterval = currentTime
}
updateWithTimeSinceLastUpdate(timeSinceLastUpdate)
}
}
here the GameOverScene file:
import UIKit
import SpriteKit
class GameOverScene: SKScene {
override init(size:CGSize){
super.init(size:size)
self.backgroundColor = SKColor.whiteColor()
var message:NSString = NSString()
message = "Game Over"
var label:SKLabelNode = SKLabelNode(fontNamed:"DamascusBold")
label.text = message
label.fontColor = SKColor.blackColor()
label.position = CGPointMake(self.size.width/2, self.size.height/2)
self.addChild(label)
var scene:GameScene!
self.runAction(SKAction.sequence([SKAction.waitForDuration(3.0),
SKAction.runBlock({
// var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
var scene1:SKScene = GameScene(size: self.size)
self.view?.presentScene(scene1)
})
] ))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
gameviewcontroller file:
import UIKit
import SpriteKit
import AVFoundation
class GameViewController: UIViewController, UITextFieldDelegate{
var scene:GameScene!
func swipedRight(sender: UISwipeGestureRecognizer){
scene.swipedRight1(sender)
}
func swipedLeft(sender: UISwipeGestureRecognizer){
scene.swipedLeft1(sender)
}
func swipedDown(sender: UISwipeGestureRecognizer){
scene.swipedDown1(sender)
}
func swipedUp(sender: UISwipeGestureRecognizer){
scene.swipedUp1(sender)
}
override func viewDidLoad() {
super.viewDidLoad()
let skView = view as SKView
skView.multipleTouchEnabled = false
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = SKSceneScaleMode.AspectFill
skView.presentScene(scene)
let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:"))
swipeRight.direction = .Right
view.addGestureRecognizer(swipeRight)
let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedLeft:"))
swipeLeft.direction = .Left
view.addGestureRecognizer(swipeLeft)
let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
swipeUp.direction = .Up
view.addGestureRecognizer(swipeUp)
let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
swipeDown.direction = .Down
view.addGestureRecognizer(swipeDown)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
You're calling your swipedUp1 (etc) methods on the wrong scene. Here's what's happening:
Your view controller has a reference to the GameScene instance that you start with. Its gesture action methods call to that, and all is well.
When you start a new game from GameOverScene, that creates a new instance of GameScene and presents it in the view. Now you have two instances of GameScene: the one your view controller is still pointing to, and the one the view is now rendering.
When you're gesture actions fire, they're still talking to the first GameScene. So your log lines get printed, but you don't see anything happen because the second GameScene is the one being displayed.
You probably don't want two scenes sticking around, anyway.
You can fix both problems by eliminatimg the scene property in your view controller and having your gesture actions call through to view.scene instead (after appropriate casting):
func swipedUp(sender: UISwipeGestureRecognizer) {
let skView = view as SKView
let gameScene = skView.scene as GameScene
gameScene.swipedUp1(sender)
}
This way, the swipe goes to whichever scene the view controller's view is currently presenting.
Alternatively, you could keep your original swipedUp (etc) code, and change scene from a stored property to a read-only computed one that always gets you the currently presented scene:
var scene: GameScene {
let skView = view as SKView
return skView.scene as GameScene
}

Resources