我正在开发一个平台游戏,并试图让我的敌人来回移动一定距离。基本上我需要找到一种方法将 dis 增加到某个数字,将其减少到零,然后再次将其增加到相同的数字。它需要无限期地继续这样做。现在它增加到 10,但随后保持不变。任何帮助将不胜感激。(注意:此代码只是一个测试版本,删除了所有"self"。
speed = 1
dis = 0
while True:
if speed > 0:
dis += 1
if dis > 10:
speed = -1
dis -= 1
if dis < 0:
speed = 1
print(dis)
你为什么不试着把它拆开呢?根据当前距离,设置速度。然后根据当前速度,增加或减少您的距离。
speed = 1
dis = 0
while True:
if dis >= 10:
# Set speed
if dis <= 0:
# Set speed
# Based on speed, increment or decrement distance
speed = 1
dis = 0
while True:
dis += speed
if dis >= 10:
speed = -1
elif dis <= 0:
speed = 1
dis += speed
可以在if/elif
之前或之后if/elif
以获得预期的结果。
或者您甚至可以使用speed = -speed
来改变方向
speed = 1
dis = 0
while True:
dis += speed
if dis <= 0 or dis >= 10:
speed = -speed
我想通了:)
speed = 1
dis = 0
while True:
if speed >= 0:
dis += 1
if dis >= 10:
speed = -1
if speed <= 0:
dis -= 1
if dis <= 0:
speed = 1
print(dis)
您可以检查对象是否在该区域之外,然后反转速度。 pygame.Rect
有很多属性,如left
和right
,在这里会有所帮助。
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray13')
BLUE = pg.Color('dodgerblue1')
rect = pg.Rect(300, 200, 20, 20)
distance = 150
speed = 1
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Check if the rect is outside of the specified
# area and if it's moving to the left or right.
if (rect.right > 300+distance and speed > 0
or rect.left < 300 and speed < 0):
speed *= -1 # Invert the speed.
# Add the speed to the rect's x attribute to move it.
rect.x += speed
# Draw everything.
screen.fill(BG_COLOR)
pg.draw.rect(screen, BLUE, rect)
pg.display.flip()
clock.tick(60)
pg.quit()