gpt4 book ai didi

iOS 8 检测 SKSpriteNode 是否被 SKLightNode 点亮

转载 作者:搜寻专家 更新时间:2023-11-01 05:40:49 25 4
gpt4 key购买 nike

我的场景中有几个 Sprite 节点正在转换阴影。我还有一个 Sprite 在其中一个阴影中。我希望能够判断用户是否将 Sprite 从阴影中移到光线中。无论如何要 swift 做到这一点?谢谢。

最佳答案

不幸的是,这个功能仍然没有包含在 SpriteKit 中,但是有可能实现一个像样的解决方案,但有一些注意事项。

要确定 Sprite 是否转换阴影,它的 shadowCastBitMask属性“通过执行逻辑 AND 运算针对灯的 categoryBitMask 属性进行测试。”根据 shadowColor 文档中给出的描述,SpriteKit 似乎为光照和物理体计算生成了完全相同的 mask 数据。 SKLightNode 上定义的属性:

When lighting is calculated, shadows are created as if a ray was cast out from the light node's position. If a sprite casts a shadow, the rays are blocked when they intersect with the sprite's physics body. Otherwise, the sprite's texture is used to generate a mask, and any pixel in the sprite node's texture that has an alpha value that is nonzero blocks the light.

SKPhysicsWorld 有一个方法,enumerateBodies(alongRayStart:end:using:),用于高效地执行这种光线相交测试。这意味着我们可以测试一个 Sprite 是否被任何具有物理体的 Sprite 遮挡。所以我们可以写一个这样的方法来扩展SKSpriteNode:

func isLit(by light: SKLightNode) -> Bool {
guard light.isEnabled else {
return false
}

var shadowed = false

scene?.physicsWorld.enumerateBodies(alongRayStart: light.position, end: position) { (body, _, _, stop) in
if let sprite = body.node as? SKSpriteNode, light.categoryBitMask & sprite.shadowCastBitMask != 0 {
shadowed = true

stop.pointee = true
}
}

if shadowed {
return false
} else {
return true
}
}

我们还可以检索场景中的哪些灯正在照亮特定的 Sprite :

func lights(affecting sprite: SKSpriteNode) -> [SKLightNode] {
let lights = sprite.scene?.children.flatMap { (node) -> SKLightNode? in
node as? SKLightNode
} ?? []

return lights.filter { (light) -> Bool in
sprite.isLit(by: light)
}
}

如果 SpriteKit 提供一种方法来检索此信息而不将其耦合到物理 API,或者要求开发人员滚动他们自己的光线转换实现,那就太好了。

关于iOS 8 检测 SKSpriteNode 是否被 SKLightNode 点亮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com