哎呀,我想删除它,但它不让我删除,抱歉,
最佳答案
它确实想以一种不碰撞的方式改变方向。 movedirection()
知道它的行驶方向,因此可以从选择中删除该方向。
def movedirection(self, x, y):
next_movement = ( x, y ) # no change
self.rect.x = self.rect.x + x
self.rect.y = self.rect.y + y
# If you collide with a wall, move out based on velocity
for block in block_list:
if self.rect.colliderect(block.rect):
if x > 0: # Moving right Hit the left side of the wall
self.rect.right = block.rect.left
directions = [(-2,0),(0,-2),(0,2)] # L, D, U
elif x < 0: # Moving left Hit the right side of the wall
self.rect.left = block.rect.right
directions = [( 2,0),(0,-2),(0,2)] # R, D, U
if y > 0: # Moving down Hit the top side of the wall
self.rect.bottom = block.rect.top
directions = [(-2,0),(2,0),(0,-2)] # L, R, D
elif y < 0: # Moving up Hit the bottom side of the wall
self.rect.top = block.rect.bottom
directions = [(-2,0),(2,0),(0,2)] # L, R, U
# pick a new random direction that does not re-collide
next_movement = random.choice( directions )
# The enemy either continues, or turned
return next_movement
显然,移动逻辑需要更改以合并返回结果:
def move(self, x, y):
return self.movedirection( x, y )
def movmethod(self,godirection,changedirection):
while True:
godirection = move( godirection )
但是 movmethod()
仍然有一个令人讨厌的无限循环(它永远不会返回)。我将按照 PyGame Sprite 类通常使用 update()
函数处理此操作的方式对运动进行建模。这处理移动和位图更改等。
def update( self ):
x, y = self.godirection # NOTE: now a member variable
self.rect.x = self.rect.x + x
self.rect.y = self.rect.y + y
# If you collide with a wall, move out based on velocity
for block in block_list:
if self.rect.colliderect( block.rect ):
if x > 0: # Moving right Hit the left side of the wall
self.rect.right = block.rect.left
directions = [(-2,0),(0,-2),(0,2)] # L, D, U
elif x < 0: # Moving left Hit the right side of the wall
self.rect.left = block.rect.right
directions = [( 2,0),(0,-2),(0,2)] # R, D, U
if y > 0: # Moving down Hit the top side of the wall
self.rect.bottom = block.rect.top
directions = [(-2,0),(2,0),(0,-2)] # L, R, D
elif y < 0: # Moving up Hit the bottom side of the wall
self.rect.top = block.rect.bottom
directions = [(-2,0),(2,0),(0,2)] # L, R, U
# pick a new random direction that does not re-collide
self.godirection = random.choice( directions )
在主循环中调用update()
。
关于python - 如何让敌人接触方 block 后随机改变方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59035867/