我有两个 SKSpriteNodes
,它们是纯色(红色和蓝色)的基本矩形。
当用户拖动它们时。我想检查两个节点是否相交,并更改第一个节点与第二个节点相交部分的颜色。
我可以通过使用节点的 .intersects(..)
属性判断节点是否相交。
但我不知道如何获取实际的交叉区域以及如何为节点的该部分着色与其原始颜色不同。
最佳答案
它可能会有点奇怪,但是在您的节点通过相交检查后:
//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)
我们现在有了交集矩形,所以让我们制作一个彩色 Sprite
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)
我们现在有一个不同颜色的盒装区域。
但是我们的 Sprite 不是正方形?你可能会问。
这就是 SKCropNode
发挥作用的地方。
让我们制作一个裁剪节点。
let croppedNode = SKCropNode()
我们想要添加 sprite1 作为 mask 节点
croppedNode.maskNode = sprite1.copy() as? SKNode
然后将其作为子元素添加到 sprite1 sprite1.addChild(croppedNode)
我们现在有了一个带有 Sprite 蒙版的裁剪节点,让我们将迷你节点移动到这个新的裁剪节点
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)
}
关于swift - SpriteKit : Change color of part of sprite which is intersecting with another sprite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45111897/