简体   繁体   English

在pygame中,如何使用箭头键控制的对象不移动屏幕边缘

[英]In pygame how to make an object controlled with arrow keys not move of the edge of the screen

I have made an object controlled with arrow keys. 我已经制作了一个用箭头键控制的对象。 When I move it to the edge of the pygame screen, the object moves off the screen. 当我将其移至pygame屏幕的边缘时,该对象将移出屏幕。 I was wondering how to keep the object on the screen. 我想知道如何将对象保留在屏幕上。 Any suggestions? 有什么建议么?

On each handle of the input, check if the object's target x position plus its width exceeds the width of the canvas or if it is less than 0 . 在输入的每个手柄上,检查对象的目标x位置及其宽度是否超​​过画布的宽度,或者是否小于0 Deny the movement if so. 如果是这样,则拒绝运动。

Repeat for the y coordinate and the height. 重复输入y坐标和高度。

Do something like this: 做这样的事情:

if player.x == #edge of screen:
    player.x -= 0
if player.y == #edge of screen:
    player.y -= 0

player.x being the players current x position and player.y being the players current y position or you can do the same thing but when the player goes of the screen it automatically goes to the other side of the screen it will probably take some tweaking to get it to look perfect player.x是玩家当前的x位置, player.y是玩家当前的y位置,或者您可以执行相同的操作,但是当玩家player.y屏幕时,它会自动转到屏幕的另一侧,因此可能需要进行一些调整使它看起来完美

last = player.rect.copy()
player.update()
if not screen.get_rect().contains(player.rect):
    player.rect = last

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

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