How do i change the code so that the player stops at the edges rather than wrapping around?

心不动则不痛 提交于 2020-06-28 04:13:11

问题


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

I want to make the player stop at the edges instead of wrapping around and teleporting to the other side. Help would be very appreciated.


回答1:


You have it the wrong way around:

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



回答2:


There's already an answer but I think that this code would be more efficient.

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


来源:https://stackoverflow.com/questions/62284058/how-do-i-change-the-code-so-that-the-player-stops-at-the-edges-rather-than-wrapp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!