Note: This is different to my previous question. The previous question I posted was about the enemy following the player, but here I want the zombie to roam around. My plan is to link these together (once they both work correctly) and have the zombie roam around until the player is within a certain radius. I would appreciate if this can be reopened as this is a different problem!
So i am trying to create an enemy that moves around the map and 'bounces' off any walls it collides with. I have tried to adapt some code i used making pong a while ago. I tried to break the problem down and consider where the enemy is hitting the wall from, but i feel like i may be overcomplicating it? Here is a video of the bug: https://i.stack.imgur.com/dpm1q.jpg
This is my current code.
class Enemy(pygame.sprite.Sprite):
def __init__(self, position):
super().__init__(enemy_group, all_sprites_group)
self.position = pygame.math.Vector2(position)
self.wander_speed = pygame.math.Vector2((6 * random.choice((-1,1))), (6 * random.choice((-1,1))))
def walk_around(self):
self.velocity = self.wander_speed
print(self.velocity)
self.position += self.velocity
self.base_zombie_rect.centerx = self.position.x
self.base_zombie_rect.centery = self.position.y
self.base_zombie_rect.centerx, self.base_zombie_rect.centery = self.position.x, self.position.y
self.check_collision_2()
self.rect.center = self.base_zombie_rect.center
self.position = (self.base_zombie_rect.centerx, self.base_zombie_rect.centery)
def check_collision_2(self):
for sprite in obstacles_group:
if sprite.rect.colliderect(self.base_zombie_rect):
if self.base_zombie_rect.top < sprite.rect.bottom and self.base_zombie_rect.centery > sprite.rect.bottom: # UP collision
print("UP COLLISION")
self.velocity.y *= -1
if self.base_zombie_rect.bottom > sprite.rect.top and self.base_zombie_rect.centery < sprite.rect.top: # DOWN collision
print("DOWN COLLISION")
self.velocity.y *= -1
if self.base_zombie_rect.left < sprite.rect.right and self.base_zombie_rect.centerx > sprite.rect.right: # LEFT collision
print("RIGHT COLLISION")
self.velocity.x *= -1
if self.base_zombie_rect.right > sprite.rect.left and self.base_zombie_rect.centerx < sprite.rect.left: # RIGHT collision
print("LEFT COLLISION")
self.velocity.x *= -1