Skip to content
Advertisement

collision issue with pygame in python3 using tiled

im working on a litle game using pygame in python3. Im using tiled for the map and pyscroll for the camera and i don’t know how to solve this issue: i made detection collision that work using object layer in tiled and a litle bit of code. the detection work pretty well but when it come to say to the ply “u can’t go this way there is a wall” im stuck… Usually, i first create a array where i put all the wall that you will collide in with a for loop, then i give my ply object x and y coordinate: i use them to make him spawn at a certaine position in the map but also i update this coordinate every frame in a variable. finally i store this coordinate in a other variable with the copy() function so i have 2 variable: position and old_position.

Then, i check every frame if there is a collision with walls and if they are collision: position = old_position | so the ply never pass through the wall. This time its not working and i really don’t know why ‘– any suggestions?

plr = Player(320, 320)
map_g.add(plr)
walls = []
for obj in tmx_data.objects:
    if obj.type == "collision":
        walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))

Loop

plr.save_pos()
map_g.center(plr.rect.center)
map_g.update(0.075)
for sprite in map_g.sprites():
    if sprite.feet.collidelist(walls) > -1:
        print("collision")
        sprite.collision_repos()
map_g.draw(win)

Ply Class

def __init__(self, pos_x, pos_y):
    super().__init__()
    ...    
    self.position = [pos_x, pos_y]
    self.old_position = self.position.copy()
    ...

def save_pos(self):
    self.old_position = self.position.copy()

def collision_repos(self):
    self.position = self.old_position
    self.rect.topleft = self.position
    self.feet.midbottom = self.rect.midbottom

def update(self, speed):
    self.rect.topleft = self.position
    self.feet.midbottom = self.rect.midbottom
    ...

Advertisement

Answer

So actually i solved the issue after 5h… Its actually a dumb problem so everything was working, its just that the save_pos() function was called too quick and worked one time, after that the function was broken. all you got to do here is just let the interpreter some m/s so call the function later in your code…

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement