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:
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.