0
\$\begingroup\$

what's the best logic to force the player to change its direction when he's just next to an obstacle (building, rock, tree..) ?

I know this is related to collision detection but maybe my logic isn't as good as needed or maybe it needs some improvements.

Here is the pseudocode for it :

for obstacle in obstacles:
    if player.mask.overlap(obstacle.mask, offset):
        blocked_dir = player.direction
    else:
        blocked_dir = ''

# movement
if key_pressed[K_d] and blocked_dir != 'right':
    player.x += player.speed
elif key_pressed[K_z] and blocked_dir != 'up':
    player.y -= player.speed
elif key_pressed[K_q] and blocked_dir != 'left':
    player.x -= player.speed
elif key_pressed[K_s] and blocked_dir != 'down':
    player.y += player.speed
# There are also other 4 directions (topright, topleft, bottomleft, bottomright) and they all have the same logic. 

So the problem with this code is that it's not accurate : sometimes the player glitches and overlaps the obstacle a bit and sometimes he can't move in a direction other than the blocked one since he's still in collision with the obstacle. (that other direction in this case becomes the blocked one).

So is there a better logic ? If not, how can I fix my own ?

\$\endgroup\$
0
\$\begingroup\$

After taking a look at the comments of a similar post, I could fix the issue.

My logic of detecting collision with map obstacles was not wrong, but it was missing something : preventing the player from getting stuck at the obstacle just after colliding with it.

The lack of this feature in my game made the player overlap with obstacles once he hits them and made the game look unrealistic.

So I had to push the player back once he collides with an obstacle depending on his last direction.

Here is the code for that :

def push_backwards(self):
    if self.blocked_dir == 'up':
        self.y += 5
    elif self.blocked_dir == 'down':
        self.y -= 5
    elif self.blocked_dir == 'right':
        self.x -= 5
    elif self.blocked_dir == 'left':
        self.x += 5
    ...

for obstacle in obstacles:
    if player.mask.overlap(obstacle.mask, offset):
        player.blocked_dir = player.direction
        player.push_backwards()
    else:
        player.blocked_dir = ''
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.