Reputation: 15
I am trying to implement a moving enemy that moves from side to side and when coming into contact with a platform changes direction and moves the other way. I have managed to make my enemy platform move in one direction but i cant seem to figure out a way to make it do the above.
Upvotes: 0
Views: 170
Reputation: 901
It's hard to follow the code. Would be great if you post the relevant portion of codes next time.
This is not the absolute solution to your problem, but I hope this gives an idea. You are ought to check for 2 things: (1) if there's a tile obstructing your way and (2) if there's no tile/ground ahead to walk on unless you want your enemy object to fall.
Below is a sample code. Haven't tried running it so there may be a bug. But the idea should be there.
class Enemy:
def __init__(self, pos: Tuple[float, float], x_vel: float):
self.image = pygame.image.load("some_image.png").convert()
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = pos
self.x_vel = x_vel
def update(self, tiles: List[Tile]):
for tile in tiles:
# check for tile obstructions
future_enemy_rect = (self.rect.x + self.x_vel, self.rect.y, self.rect.width, self.rect.height)
if tile.rect.colliderect(future_enemy_rect):
self.x_vel *= -1
# check if there's no tile ground ahead: create a small 8x8 or any arbitrary rect at bottom right and left of the enemy
bottom_right_enemy_rect = (self.rect.right, self.rect.bottom, 8, 8)
bottom_left_enemy_rect = (self.rect.x - 8, self.rect.bottom, 8, 8)
if (not tile.rect.colliderect(bottom_right_enemy_rect)) or (not tile.rect.colliderect(bottom_left_enemy_rect)):
self.x_vel *= -1
There may also be other approach to this which I am not aware of.
Upvotes: 3