检查玩家是否达到了边距 [英] Check if the player has hit a margin

查看:21
本文介绍了检查玩家是否达到了边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swift 制作一个小游戏,一个贪吃蛇游戏.我已经尝试过使用 python 来做这个游戏,它奏效了!为了运行游戏,我使用了一个 while 循环.通过这种方式,我可以随时改变玩家的位置并检查他是否击中了边距.现在我必须再次执行此操作,但我不知道如何告诉我的程序始终检查蛇是否已经撞到了边缘或他自己.我应该做这样的事情

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()
}

因此,如果玩家在 x 或 y 轴上的位置大于屏幕尺寸或小于 0,则调用函数death()".如果我必须用 python 来做这件事,我会把所有这些代码放在主 while 循环"中.但是有了 swift ,我可以使用的时间并不长......有什么建议吗?

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?

推荐答案

使用 SpriteKit.新建项目时可以选择这个,选择Game,然后选择SpriteKit.这是Apple制作游戏的框架.它有你需要的东西,而且速度更快 - 不要用 UIKit 制作游戏.

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.

在 SpriteKit 中,您有 update() 方法,作为 SKScene 的一部分.不要使用 while 循环.这些是非常不可靠的,蛇的速度会因设备而异.

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:

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)
        }
    }
}

完成所有这些之后,您最终可以检查蛇是否超出了此 update() 循环中的某些边距或其他内容.尽量减少 update() 循环中的代码,因为它通常以每秒 60 次的速度运行.

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.

这篇关于检查玩家是否达到了边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆