如何更改代码,使播放器停在边缘而不是环绕?


WIDTH = 800
HEIGHT = 500
background = Actor("background")
player = Actor("player")
player.x = 200
player.y = 200
def draw():
screen.clear()
background.draw()
player.draw()
def update():
if keyboard.right:
player.x = player.x + 4
if keyboard.left:
player.x = player.x - 4
if keyboard.down:
player.y = player.y + 4
if keyboard.up:
player.y = player.y - 4
if player.x > WIDTH:
player.x = 0
if player.x < 0:
player.x = WIDTH
if player.y < 0:
player.y = HEIGHT
if player.y > HEIGHT:
player.y = 0

我想让玩家停在边缘,而不是绕来绕去传送到另一边。帮助将不胜感激。

你用错误的方式绕过它:

if player.x > WIDTH:
player.x = WIDTH
if player.x < 0:
player.x = 0
if player.y < 0:
player.y = 0
if player.y > HEIGHT:
player.y = HEIGHT

已经有一个答案,但我认为这段代码会更有效率。

def update():
if keyboard.right and player.x<=WIDTH-4:
player.x = player.x + 4
if keyboard.left and player.x>=4:
player.x = player.x - 4
if keyboard.down and player.y<=HEIGHT-4:
player.y = player.y + 4
if keyboard.up and player.y>=4:
player.y = player.y - 4

相关内容

  • 没有找到相关文章

最新更新