Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

swift - Check if the player has hit a margin

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

New game project

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.

SKScene update loop

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...