benny hassan
benny hassan

Reputation: 301

Gravity and Collision with Walls - PYGAME

When player colliding with the wall it jump to the top of the wall. The methode worked fine with colliding with floor obstacle. But I cant see why collision with wall decrease my player.rect.y coordinate.

class player_jump:
 def __init__(self):
    self.jump = False
    self.in_aire = True
    self.vel_y = 0

 def move_y(self):
        #reset movment variables
        dy = 0

        if self.jump and not self.in_air:
            self.vel_y = -11
            self.jump = False
            self.in_air = True

        #apply gravity (global variable , GRAVITY = 0.5 )
        self.vel_y += GRAVITY
        if self.vel_y > 10:
            self.vel_y = 0
   
        dy += self.vel_y

        #check for collision (world.obstacle_list - contain data on wall and bottom rects)
        for tile in world.obstacle_list:
            #x direction
            if tile[1].colliderect(self.rect.x + dx,self.rect.y,self.rect.width,self.rect.height):
                dx = 0
              
            #y direction
            if tile[1].colliderect(self.rect.x,self.rect.y + dy,self.rect.width,self.rect.height):
                #check if below the ground , i.e jumping
                if self.vel_y < 0:
                    self.vel_y = 0
                    dy = tile[1].bottom - self.rect.top
                    self.in_air = False
                #check if above the ground i.e falling
                elif self.vel_y >= 0:
                    self.in_air = False
                    dy = tile[1].top - self.rect.bottom
                    
        # update rectangle position
        self.rect.x += dx
        self.rect.y += dy

Upvotes: 1

Views: 356

Answers (1)

Rabbid76
Rabbid76

Reputation: 210889

Your algorithm depends on the order of the tiles. Make the algorithm order independent for collision detection along the axis.

First run the collision check along the x-axis for all tiles. Then run the collision check along the y-axis for all tiles. When running the test along the y-axis, you also need to account for movement along the x-axis:

# x direction
test_rect = self.rect.move(dx, 0)
for tile in world.obstacle_list:
    if tile[1].colliderect(test_rect):
        dx = 0
        break
              
# y direction
for tile in world.obstacle_list:
            
    test_rect = self.rect.move(dx, dy)
    if tile[1].colliderect(test_rect):
        # [...]

Upvotes: 1

Related Questions