bob
bob

Reputation: 185

How do you tell if a node is on the screen spritekit swift

I am trying to figure out how to determine if a node is visible on the screen or off the screen. Is this just a true/false property of the node? Thanks. (Using swift spritekit)

Upvotes: 12

Views: 8300

Answers (6)

Anton Shevtsov
Anton Shevtsov

Reputation: 190

the best answer here will be:

if scene.frame.contains(myNode.position) {
//do stuff
}

"intersect" method is very heavy and involves too much computing, can produce lag if used on many instances

Upvotes: 6

DevinDazzle
DevinDazzle

Reputation: 41

If you put a SKCameraNode in the scene, you can check if a node is inside the view of the camera using the contains method:

https://developer.apple.com/documentation/spritekit/skcameranode

You can also get all the nodes visible to the camera using the containedNodeSet instance method.

Upvotes: 3

Kevin Owens
Kevin Owens

Reputation: 548

If your SKScene fits within its containing view, this should work:

if !node.intersectsNode(node.parent!) {
     // node is off-scene/out-of-view
}

where node is an SKNode that is the child of your SKScene.

Upvotes: 0

0x141E
0x141E

Reputation: 12753

You can use the following to test if a node is in the scene:

if (!intersectsNode(sprite)) {
  println("node is not in the scene")
}

This assumes that self is an SKScene subclass, such as GameScene.

Upvotes: 20

LinusG.
LinusG.

Reputation: 28892

Not directly but you could use its position to check. Therefore you might do something like:

if (/*the node's position is between 0 and the screen's .x and .y*/) {
    //on screen
}

Hope that helps :)

Upvotes: 0

ABakerSmith
ABakerSmith

Reputation: 22939

You could use CGRectIntersectsRect supplying the frame of your SKSpriteNode and the SKScene. For example:

if !CGRectIntersectsRect(frame, spriteNode.frame) {
    // Outside the bounds of the scene because the frames are no longer intersecting.
}

Upvotes: 0

Related Questions