我想在pygame中来回移动对象,但它只向左移动,然后停止



我试图来回移动我的老板精灵,但它只向左移动并停留在那里我的代码有什么问题。

def horizontal_movement(self):
self.rect.x-=1
if self.rect.left<0: #when boss reaches extreme left
self.rect.x+=1 #move right
if self.rect.right==screen_width: #when boss reaches extreme right
self.rect-=1 #move left
if self.rect.midbottom==[boss_x,boss_y]: #stop the motion when boss reaches original position
pass

添加一个指示移动方向的属性。当敌人到达边境时改变方向:

class YourClassName:
def __init__(self):
# [...]

self.direction = -1
def horizontal_movement(self):
self.rect.x += self.direction
if self.rect.left <= 0: #when boss reaches extreme left
self.direction = 1
elif self.rect.right <= screen_width: #when boss reaches extreme right
self.direction = -1

if self.rect.midbottom==[boss_x,boss_y]: #stop the motion when boss reaches original position
pass
  1. 在迭代此代码时,您总是向左移动(-1(。无论第一步是什么,每次迭代都只剩下1步
  2. 一旦你碰到屏幕的边缘,你就向右移动一个位置。代码再次迭代,然后向左移回1个位置(正如我上面指出的第一行代码(

这种模式永远重复:每次迭代向左移动一个空格,直到碰到屏幕边缘,然后在屏幕边缘和右侧一个位置之间来回移动,一次又一次。

相反,self.rect.x-=1应该在(-1和1(之间随机,以便在每次迭代中随机向右或向左移动?

代码的问题是,它向左移动1,但随后又向右移动,因为if self.rect.right==screen_width: #when boss reaches extreme right的计算结果为false你可以这样做:

self.right_movement = False
def horizontal_movement(self):
if self.right_movement:
if self.rect.bottom <= boss_x:
self.right_movement = False
self.rect.x += 1
else:
if self.rect.right >= screen_width:
self.right_movement = True
self.rect.x -= 1

最新更新