我的敌人精灵在我的游戏中移动相对较慢。当我将速度提高到超过1的任何速度时,它们在左方向上移动得非常快,在向右方向上移动速度有点慢。有谁知道这背后的原因?
class Enemy(pygame.sprite.Sprite):
def __init__(self,x,y,width = 60, height = 55):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.speed = 1
self.s0 = pygame.image.load("Images/Enemy/s0.png")
s1 = pygame.image.load("Images/Enemy/s1.png")
s2 = pygame.image.load("Images/Enemy/s2.png")
s3 = pygame.image.load("Images/Enemy/s3.png")
rs0 = pygame.transform.flip(self.s0 ,True, False)
rs1 = pygame.transform.flip(s1 ,True, False)
rs2 = pygame.transform.flip(s2 ,True, False)
rs3 = pygame.transform.flip(s3 ,True, False)
self.attack = pygame.image.load("Images/Enemy/attack.png")
self.rattack = pygame.image.load("Images/Enemy/rotatedattack.png")
self.images = []
self.images.append(self.s0)
self.images.append(s1)
self.images.append(s2)
self.images.append(s3)
self.rotated_images = []
self.rotated_images.append(rs0)
self.rotated_images.append(rs1)
self.rotated_images.append(rs2)
self.rotated_images.append(rs3)
self.deadimages= [self.attack]
self.index = 0
self.TimeNum=0
self.TimeTarget=10
self.image = self.images[self.index]
self.rect = pygame.Rect(self.x,self.y,width,height)
self.playercollision = False
self.Timer = 0
def update(self,player):
if self.rect.colliderect(player.rect):
print("hey")
self.Timer += 1
if self.Timer >= 10:
if self.rect.x > player.rect.x:
self.image = self.attack
if self.rect.x < player.rect.x:
self.image = self.rattack
if player.rect.x == 0:
self.image = self.s0
def Enemy1Move(self,player):
if player.rect.x > 0 and player.rect.x < 655:
if self.rect.x < player.rect.x:
self.rect.x += self.speed
self.TimeNum+=1
if self.TimeNum == self.TimeTarget:
self.index +=1
if self.index >= len(self.rotated_images):
self.index = 0
self.image = self.rotated_images[self.index]
self.TimeNum = 0
if self.rect.x > player.rect.x:
self.rect.x -= self.speed
self.TimeNum +=1
if self.TimeNum == self.TimeTarget:
self.index +=1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
self.TimeNum = 0
答案 0 :(得分:1)
由于Jongware在评论中已经感到悲伤,因此问题可能是if
语句在Enemy1Move
的同一次调用中可能都是真的。
说self.speed
为5,self.rect.x
为100,player.rect.x
为102。
现在if self.rect.x < player.rect.x:
为真,self.rect.x += self.speed
将self.rect.x
更改为105。
当该功能仍在运行时,下一个if
声明if self.rect.x > player.rect.x:
也是如此,self.rect.x -= self.speed
将self.rect.x
更改回100。
考虑使用elif
:
if self.rect.x < player.rect.x:
self.rect.x += self.speed
...
elif self.rect.x > player.rect.x:
self.rect.x -= self.speed
...