For a game I'm creating, an SKSpriteNode gradually makes its way down the user's screen. There's another SKSpriteNode (position is static) near the bottom of the screen, leaving only a little bit of space for the original SKSpriteNode to fit in. I need to detect when the first SKSpriteNode is COMPLETELY below the second SKSpriteNode, which I'm having a bit of trouble with. Here's the code I'm currently using:
对于我正在创建的游戏,SKSpriteNode逐渐沿着用户的屏幕向下移动。在屏幕底部附近还有另一个SKSpriteNode(位置是静态的),只留下一点空间让原始SKSpriteNode适合。我需要检测第一个SKSpriteNode何时完全低于第二个SKSpriteNode,我有有点麻烦。这是我目前使用的代码:
if (pos.y > barPosY) //pos.y = 1st SKSpriteNode, barPosY = 2nd SKSpriteNode
{
touchedTooEarly = true
}
For some reason, when the first SKSpriteNode goes just a little bit over the 2nd SKSpriteNode (not all the way), it still detects it as being completely over. Is there a coordinate space issue I'm missing?
出于某种原因,当第一个SKSpriteNode稍微超过第二个SKSpriteNode(不是一直)时,它仍然会检测到它完全结束。是否存在我缺少的坐标空间问题?
Thanks
1 个解决方案
#1
1
The logic
A sprite a
covers a sprite b
if
一个精灵a覆盖一个精灵b if
-
b.frame
is insidea.frame
-
b.zPosition
is belowa.zPosition
b.frame在a.frame内
b.zPosition低于a.zPosition
The extension
Now let's build an extension
现在让我们构建一个扩展
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)
}
}
Problem #1: transparency
This mechanism totally ignores transparency.
这种机制完全忽略了透明度。
Problem #2: same sprite
If you compare 2 sprites of the same type the function CGRectContainsRect
will return true only when they are exactly aligned. Althoug you can solve this problem creating a smaller rectangle when you compare the sprites.
如果比较相同类型的2个精灵,则函数CGRectContainsRect仅在精确对齐时才返回true。虽然你可以解决这个问题,比较精灵时创建一个较小的矩形。
#1
1
The logic
A sprite a
covers a sprite b
if
一个精灵a覆盖一个精灵b if
-
b.frame
is insidea.frame
-
b.zPosition
is belowa.zPosition
b.frame在a.frame内
b.zPosition低于a.zPosition
The extension
Now let's build an extension
现在让我们构建一个扩展
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)
}
}
Problem #1: transparency
This mechanism totally ignores transparency.
这种机制完全忽略了透明度。
Problem #2: same sprite
If you compare 2 sprites of the same type the function CGRectContainsRect
will return true only when they are exactly aligned. Althoug you can solve this problem creating a smaller rectangle when you compare the sprites.
如果比较相同类型的2个精灵,则函数CGRectContainsRect仅在精确对齐时才返回true。虽然你可以解决这个问题,比较精灵时创建一个较小的矩形。