简体   繁体   中英

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.

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:

    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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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