0

I am working on a little game with Pygame and I stumbled across a little thing I couldn't fix by myself. I want that the enemy moves towards the Player, but the way I do it now has some issues. One of it is, that the enemy is faster on the positive coordinates and the second problem is that the program crashes when the enemy is directly on the "player"

Here is the problematic code and an example video:

    px, py = player_rect.center
    sx, sy = snail_rect.center
    
    
    direction = (px - sx, py - sy)

    dx, dy = (px - sx, py - sy)

    length = math.sqrt(dx*dx + dy*dy)
    dx /= length
    dy /= length

    c = 3
    dx = c * dx
    dy = c * dy

    snail_rect.center = (sx + dx, sy + dy)

This is the video I mentioned

I don't think the math is wrong, but I can't find why it's getting slower on the negative x and y coordinate.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DapiLP
  • 23
  • 4
  • `pygame.rect` can just store integral coordinates. See [Pygame doesn't let me use float for rect.move, but I need it](https://stackoverflow.com/questions/63468413/pygame-doesnt-let-me-use-float-for-rect-move-but-i-need-it/63468637#63468637) – Rabbid76 Aug 25 '21 at 15:06
  • 1
    Don't divide by length when it is 0 – planetmaker Aug 25 '21 at 15:10
  • Besides the division by zero when length==0, the video makes sense to me. It's slow when it's far from the snail, and fast when the snail gets closer. Although I'm not sure what's making it curve around and stay on screen when the code seems to say "run directly away from the snail". – joanis Aug 25 '21 at 16:13

0 Answers0