它可能有点古怪,但是在你的节点通过相交检查之后:
//Note: I am assuming both frames are on the same parent node, you may need to convert if parents are different
let intersection = sprite1.frame.intersection(sprite2.frame)
我们现在有了交集矩形,所以让我们制作一个颜色精灵
let miniSprite = SKSpriteNode(color:.red,size:intersection.size)
miniSprite.alpha = 0.5
将其添加到场景中
sprite1.parent.addChild(miniSprite)
设置位置
miniSprite.anchorPoint = CGPoint(x:0.0,y:0.0)
miniSprite.position = intersection.origin
将它移动到 sprite1(这将为我们转换位置)
miniSprite.move(toParent:sprite1)
我们现在有一个不同颜色的盒装区域。
但是我们的精灵不是正方形?你可能会问。
这就是SKCropNode 的用武之地。
让我们做一个裁剪节点。
let croppedNode = SKCropNode()
我们想添加我们的 sprite1 作为掩码节点
croppedNode.maskNode = sprite1.copy() as? SKNode
然后将它作为一个孩子添加到 sprite1
sprite1.addChild(croppedNode)
我们现在有了一个带有精灵蒙版的裁剪节点,让我们将迷你节点移动到这个新的裁剪节点
miniSprite.move(toParent:croppedNode)
我们开始了,您现在应该在交叉点出现颜色。
最终的代码应该是这样的:
let intersection = sprite1.frame.intersection(sprite2.frame)
let miniSprite = SKSpriteNode(color:.red,size:intersection.size)
miniSprite.alpha = 0.5
sprite1.parent!.addChild(miniSprite)
miniSprite.anchorPoint = CGPoint(x:0.0,y:0.0)
miniSprite.position = intersection.origin
let croppedNode = SKCropNode()
croppedNode.maskNode = sprite1.copy() as? SKNode
croppedNode.anchorPoint = CGPoint(x:0.5,y:0.5)
sprite1.addChild(croppedNode)
miniSprite.move(toParent:croppedNode)
现在要记住一些事情,
zPosition 可能需要调整
这是它的工作示例:
override func didMove(to view: SKView) {
let sprite1 = SKSpriteNode(imageNamed: "Spaceship")
sprite1.anchorPoint = CGPoint(x:0.5,y:0.5)
sprite1.position = CGPoint.zero
sprite1.zPosition = 1
let sprite2 = SKSpriteNode(imageNamed: "Spaceship")
sprite2.anchorPoint = CGPoint(x:0.5,y:0.5)
sprite2.position = CGPoint(x:0,y:300)
addChild(sprite1)
addChild(sprite2)
let intersection = sprite1.frame.intersection(sprite2.frame)
let miniSprite = SKSpriteNode(color:.red,size:intersection.size)
miniSprite.alpha = 0.5
miniSprite.anchorPoint = CGPoint(x:0.0,y:0.0)
miniSprite.position = intersection.origin
miniSprite.zPosition = 2
sprite1.parent!.addChild(miniSprite)
let croppedNode = SKCropNode()
croppedNode.maskNode = sprite1.copy() as? SKNode
croppedNode.zPosition = 3
sprite1.addChild(croppedNode)
let biggy = SKSpriteNode(color: .white, size: (scene?.size)!)
miniSprite.move(toParent:croppedNode)
}