【问题标题】:Detecting when SKSpriteNode is completely below another SKSpriteNode检测 SKSpriteNode 何时完全低于另一个 SKSpriteNode
【发布时间】:2020-02-05 22:32:38
【问题描述】:

对于我正在创建的游戏,SKSpriteNode 逐渐出现在用户屏幕上。屏幕底部附近还有另一个 SKSpriteNode(位置是静态的),只为原始 SKSpriteNode 留下一点空间来适应。我需要检测第一个 SKSpriteNode 何时完全低于我拥有的第二个 SKSpriteNode有点麻烦。这是我目前正在使用的代码:

if (pos.y > barPosY) //pos.y = 1st SKSpriteNode, barPosY = 2nd SKSpriteNode
{
    touchedTooEarly = true
}

由于某种原因,当第一个 SKSpriteNode 稍微超过第二个 SKSpriteNode(不是一直)时,它仍然检测到它完全结束了。有没有我遗漏的坐标空间问题?

【问题讨论】:

  • 你没有考虑精灵的高度,你需要确保pos.y - pos.frame.height/2 > barPosY + bar.frame.height/2

标签: ios sprite-kit


【解决方案1】:

逻辑

一个精灵a 覆盖一个精灵b 如果

  1. b.frame 在里面 a.frame
  2. b.zPosition 低于 a.zPosition

扩展

现在让我们构建一个扩展

extension SKSpriteNode {
    func isCoveredBy(otherSprite: SKSpriteNode) -> Bool {
        let otherFrame = CGRect(
            origin: convertPoint(otherSprite.position, fromNode: otherSprite),
            size: otherSprite.frame.size
        )
        return zPosition < otherSprite.zPosition && CGRectContainsRect(frame, otherFrame)
    }
}

问题 #1:透明度

这种机制完全忽略了透明度。

问题 #2:相同的精灵

如果您比较 2 个相同类型的精灵,函数 CGRectContainsRect 只有在它们完全对齐时才会返回 true。尽管您可以在比较精灵时创建一个较小的矩形来解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多