This is my collision code. i made a temp_rect cause after colliding with the ground it started teleporting around. it works fine, but when i collide witha tile from left/right it teleports to the top
def collision_test(rect,tiles):
hit_list=[]
for tile in tiles:
if rect.colliderect(tile):
hit_list.append(tile)
return hit_list
def collision_move(rect,movement,tiles):
collision_types={"Top":False,"Bottom":False,"Left":False,"Right":False}
rect_temp=pygame.Rect(rect.x,rect.y,atom.width,atom.height-1)
rect_temp.x =movement[0]
hit_list=collision_test(rect_temp,tiles)
for tile in hit_list:
if movement[0]>0:
rect.right=tile.left
collision_types["Right"]=True
elif movement[0]<0:
rect.left=tile.right
collision_types["Left"]=True
rect_temp.y =movement[1]
hit_list=collision_test(rect_temp,tiles)
for tile in hit_list:
if movement[1]>0:
rect.bottom=tile.top
collision_types["Bottom"]=True
elif movement[1]<0:
rect.top=tile.bottom
collision_types["Top"]=True
return rect,collision_types
CodePudding user response:
First you test the collision along the x-axis. If a collision is detected, the position of the rectangle is corrected. Therefore you have to set rect_temp
again, a after the collision handling along the x-axis and before the collision handling for the y-axis:
def collision_move(rect,movement,tiles):
collision_types={"Top":False,"Bottom":False,"Left":False,"Right":False}
rect_temp=pygame.Rect(rect.x,rect.y,atom.width,atom.height-1)
rect_temp.x =movement[0]
hit_list=collision_test(rect_temp,tiles)
for tile in hit_list:
if movement[0]>0:
rect.right=tile.left
collision_types["Right"]=True
elif movement[0]<0:
rect.left=tile.right
collision_types["Left"]=True
rect_temp=pygame.Rect(rect.x,rect.y,atom.width,atom.height-1) # <- this is missing
rect_temp.y =movement[1]
hit_list=collision_test(rect_temp,tiles)
for tile in hit_list:
if movement[1]>0:
rect.bottom=tile.top
collision_types["Bottom"]=True
elif movement[1]<0:
rect.top=tile.bottom
collision_types["Top"]=True
return rect,collision_types