简体   繁体   English

如何在Swift的屏幕上方启动Sprite?

[英]How to launch Sprite from above screen in Swift?

I'm programming a game for iOS in Xcode and I'm trying to launch a colorSprite from above the screen so it falls into view. 我正在用Xcode为iOS编写游戏,并且试图从屏幕上方启动colorSprite,以使其进入视野。

However, I have also formed a border so that no sprites bounce outside view... 但是,我也形成了一个边界,以使没有精灵在外面反弹。

    let border = SKPhysicsBody(edgeLoopFrom: self.frame)

As a result, the colorSprite doesn't enter view when I apply Impulse like such: 结果,当我像这样应用Impulse时,colorSprite不会进入视图:

    ball.physicsBody?.applyImpulse(CGVector(dx: -20, dy: -20))

A possible solution would be to activate the border after the sprite has entered but the game I'm making requires colorSprites to constantly fall from the top like raindrops but stay within the borders once entered into view. 一种可能的解决方案是在精灵进入后激活边框,但我正在制作的游戏要求colorSprite像雨滴一样不断从顶部掉落,但一旦进入视野,就必须留在边框内。

I hope I've explained it a logically as possible, what would be the solution please? 我希望我已在逻辑上进行了解释,请问解决方案是什么?

Make the top border a different category to the other borders: 使顶部边框与其他边框不同:

let borderCategory:     UInt32 = 1 << 0
let topBorderCategory:       UInt32 = 1 << 1

Then, in update() , iterate over all of your sprites and if they are moving down, stop them from colliding with the top border. 然后,在update() ,遍历所有精灵,如果它们向下移动,则阻止它们与顶部边框碰撞。 If they are moving up, allow them to collide: 如果它们向上移动,请允许它们发生碰撞:

enumerateChildNodes(withName: "//*") { node, _ in
    if let sprite = node as? SKSpriteNode {

        if (sprite.physicsBody?.velocity.dy)! > CGFloat(0) {
            sprite.physicsBody?.collisionBitMask &= ~self.topBorderCategory
        }

        if (sprite.physicsBody?.velocity.dy)! <= CGFloat(0) {
            sprite.physicsBody?.collisionBitMask |= self.topBorderCategory
        }
    }
}

Now you effectively have a one-way border. 现在,您有效地有了单向边界。

PS This would be better implemented not in update() but as a property observer on the physicsBody velocity property, but I cannot get that to work. PS最好不要在update()实现,而应作为physicsBody velocity属性的属性观察器实现,但我无法使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM