0

I want to check if 2 custom SKShapeNodes intersect.

I know Apple has SKNode.intersect(SKNode), which is what I’m attempting to use here.

Here’s some basic code to check if two triangles collide (I’m planning to substitute triangles for more complex polygons)

let triangle1 = CGMutablePath()
let triangle2 = CGMutablePath()

// Triangle 1
triangle1.move(to: CGPoint(x: 0, y: 0))
triangle1.addLine(to: CGPoint(x: 1, y: 0))
triangle1.addLine(to: CGPoint(x: 0, y: 1))
triangle1.addLine(to: CGPoint(x: 0, y: 0)) 
let triangle1_shapeNode = SKShapeNode(path: triangle1)

// Triangle 2 
triangle2.move(to: CGPoint(x: 1, y: 1))  
triangle2.addLine(to: CGPoint(x: 2, y: 1))
triangle2.addLine(to: CGPoint(x: 1, y: 2))
triangle2.addLine(to: CGPoint(x: 1, y: 1))
let triangle2_shapeNode = SKShapeNode(path: triangle2)

The triangles are positioned liked so: triangles set up visually

These triangles obviously don’t intersect visually, but it has to be with the bounding box that they intersect.

 triangle1_shapeNode.intersects(triangle2_shapeNode)
 //returns true

I was following https://stackoverflow.com/a/27667860 to see if I can get them to not intersect on the white space.

// Triangle 1 
triangle1_shapeNode.fillColor = .red 
let triangle1_texture = view.texture(from: triangle1_shapeNode)
let triangle1_sprite = SKSpriteNode(texture: triangle1_texture)
let triangle1_cropNode = SKCropNode()
triangle1_cropNode.maskNode = triangle1_sprite
triangle1_cropNode.addChild(triangle1_shapeNode)

// Triangle 2 
triangle2_shapeNode.fillColor = .blue 
let triangle2_texture = view.texture(from: triangle2_shapeNode)
let triangle2_sprite = SKSpriteNode(texture: triangle2_texture)
let triangle2_cropNode = SKCropNode()
triangle2_cropNode.maskNode = triangle2_sprite
triangle2_cropNode.addChild(triangle2_shapeNode)

But that did not solve the issue as here are some interesting statements:

triangle1_cropNode.intersects(triangle1_cropNode)
// returns false — does not intersect itself ???

triangle1_sprite.intersects(triangle2_sprite) 
// returns true
// the sprites extracted from a texture did not do 
// anything with the bounding box

Any help would be appreciated to find out how I can make a “bounding box” that would only encapsulate my polygons given a path.

skarchmit
  • 441
  • 5
  • 14
  • You are not dealing with bounding boxes, because you are working with triangles. You need an advanced method. You could use SKPhysics, or you can write your own method to check when 2 polygons intersect – Knight0fDragon Sep 02 '19 at 22:35
  • @Knight0fDragon these are triangles in the examples, but my polygons would be a mixture of triangles and squares, would that be even more advanced checking? BTW, when I tried physics body, it gave me the same results (SKPhysicsBody without affected by gravity.) should I be applying some mask on the body? – skarchmit Sep 02 '19 at 23:24
  • No a mask wont do anything. You need to use a polygon body – Knight0fDragon Sep 02 '19 at 23:37

0 Answers0