Check if the player has hit a margin

2020-01-20 17:46发布

问题:

I'm making a little game using swift, a Snake Game. I've already tried to do this game using python and it worked! To run the game I used a while loop. In this way, I could always change the player position and check if he had hit the margins. Now I have to do this again, but I don't know how to tell to my program to check all the time if the snake has hit the margins or himself. I should do something like that

if player.position.x <= 0 || player.position.x >= self.size.width || player.position.y <= 0 || player.position >= self.size.height{
   death()
}

So, if the player position on x or y axis is major than the screen size or minor than 0, call the function "death()". If I had to do this with python, I'd have just put all this code inside the "main while loop". But with swift there's not a big while I can use... any suggestions?

回答1:

Use SpriteKit. You can select this when creating a new project, choose Game, and then select SpriteKit. It's Apple's framework to make games. It has what you will need, and is also faster - don't make games in UIKit.

Within SpriteKit, you have the update() method, as part of SKScene. Do NOT use a while loop. These are highly unreliable, and the speed of the snake will vary between devices.

Here is a small piece of code to help you get started on the SKScene:

import SpriteKit


class Scene: SKScene {

    let timeDifference: TimeInterval = 0.5  // The snake will move 2 times per second (1 / timeDifference)
    var lastTime: TimeInterval = 0

    let snakeNode = SKSpriteNode(color: .green, size: CGSize(width: 20, height: 20))


    override func update(_ currentTime: TimeInterval) {
        if currentTime > lastTime + timeDifference {
            lastTime = currentTime

            // Move snake node (use an SKSpriteNode or SKShapeNode)
        }
    }
}

After doing all this, you can finally check if the snake is over some margins or whatever within this update() loop. Try to reduce the code within the update() loop as much as possible, as it gets run usually at 60 times per second.



回答2:

If I understood you correctly: You are looking for a loop in Swift that does all the calculation and drawing for your game. Here you have some tutorials about loops in Swift. In fact there are while loops that you could use in order to answer your question. I hope I could help.



标签: swift xcode