1
我正在測試一個非常基本的項目,我似乎無法得到intersectsNode
函數的工作。在我的GameScene.swift文件中,我創建了一個名爲world的SKShapeNode
,並在其內部創建了另一個SKShapeNode
,稱爲player
,並創建了一個名爲spinningGreenSquare
的旋轉SKShapeNode
。SpriteKit-你如何檢查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")
}
}
}
感謝尼克,我將它們改爲'SpriteNode',它就像一個魅力跑。 – Austin