2015-08-21 44 views
1

我正在測試一個非常基本的項目,我似乎無法得到intersectsNode函數的工作。在我的GameScene.swift文件中,我創建了一個名爲world的SKShapeNode,並在其內部創建了另一個SKShapeNode,稱爲player,並創建了一個名爲spinningGreenSquare的旋轉SKShapeNodeSpriteKit-你如何檢查SKNodes之間的交集?

在我的GameViewController.swift文件中,我設置了一個touchesMoved函數,它可以找到觸摸位置location,並將player移動到它。現在,如下圖所示,然後測試2是否相交,並在返回值爲true時執行一些操作。當我運行我的項目時,player移動得很好,但交叉點測試總是出現錯誤,即使它們明顯在設備上相交。以下是我的項目代碼。我的聲明是不正確的,還是我沒有正確使用交叉點?

import UIKit 
import SpriteKit 

class GameViewController: UIViewController { 

let scene = GameScene(fileNamed:"GameScene") 
var touchedInPlayer = false 

func goto(target: String) { 
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let vc: UINavigationController = storyboard.instantiateViewControllerWithIdentifier(target) as! UINavigationController 
    self.presentViewController(vc, animated: false, completion: nil) 

} 


override func viewDidLoad() { 
    super.viewDidLoad() 
     // Configure the view. 
     let skView = self.view as! SKView 
     skView.ignoresSiblingOrder = true 
     scene!.scaleMode = .AspectFill 
     skView.presentScene(scene) 

} 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    let location = touches.first!.locationInNode(scene!.player) 
    let locationInWorld = touches.first!.locationInNode(scene!.world) 
    if location.x < 25 && location.x > -25 && location.y < 25 && location.y > -25 { 
     touchedInPlayer = true 
     scene!.player.position = locationInWorld 
    } 

} 
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    //finds the location of the touch 
    let location = touches.first!.locationInNode(scene!.world) 

    //tests if the touch was in the player's square and moves the player to touch 
    if scene!.player.containsPoint(location) { 
     scene!.player.position = location 
    } 

    //what should happen when the 2 squares intersect 
    if scene!.player.intersectsNode(scene!.spinningGreenSquare) { 

     goto("Another View") 
    } 

} 

}

****Link For My Code****

回答

3

通過使用此代碼嘗試使用update:函數,而不是touchesMoved:

override func update(currentTime: CFTimeInterval) { 
    if scene!.player.intersectsNode(scene!.spinningGreenSquare) { 

     goto("Another View") 
    } 

} 

另一件事你應該嘗試的是確保球員和SpinningGreenSquare都類型SKSpriteNode

希望這會有所幫助:)

+0

感謝尼克,我將它們改爲'SpriteNode',它就像一個魅力跑。 – Austin