Reputation: 421
I'm testing out a very basic project, and I can't seem to get the intersectsNode
function working. In my GameScene.swift file, I created an SKShapeNode
called world, and inside it, another SKShapeNode
called player
and a spinning SKShapeNode
called spinningGreenSquare
.
In my GameViewController.swift file, I setup a touchesMoved
function that finds the location of the touch, location
, and moves the player
to it. Now, as you'll see in the below image, I then test if the 2 intersect, and preform some actions if the return value is true. When I run my project though, the player
moves around just fine, but the intersection test always turns up `false, even though they are clearly intersecting on the device. Below is my code for the project. Is my declaration of something incorrect, or am I not using intersections properly?
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")
}
}
}
Upvotes: 4
Views: 1673
Reputation: 195
Try using the update:
function instead of touchesMoved:
by using this code:
override func update(currentTime: CFTimeInterval) {
if scene!.player.intersectsNode(scene!.spinningGreenSquare) {
goto("Another View")
}
}
Another thing you should try is making sure Player and SpinningGreenSquare are both of type SKSpriteNode
.
Hope this helps :)
Upvotes: 3