I've been learning to use Python for around one month with pygame. I want to realize my first small project, it's a Zelda-like game where you navigate a small octopus, avoid enemies (later also fight) and collect treasures.
I am able to move my character and also the enemies can walk by themself. I can use the rect method to detect collision between the player and enemy and also by walking over a rectangle to switch to another part (map) in the level.
Now I want to create obstacle which you cant pass (palm trees, rocks, etc.) the player should be forced to walk around this obstacles.
I learned already how to clip the position/side (up, bottom, right, left) from which my character (octopus) touches the obstacle (palmtree). But still my octopus will walk trough the palmtree.
def collision(source, target):
if not source.colliderect(target): return
overlap = source.clip(target)
if overlap.width > overlap.height: #verticale collision
if source.y < target.y: #top
source.bottom = target.top
#print ("oben")
else:
source.top = target.bottom
#print ("Tako_oben =" + str(source.top) + "Palme UNTEN =" + str(target.bottom))
print("Tako_oben =" + str(source.top) + "Tako_unten =" + str(source.bottom))
#print("unten")
else: # horizontale collision
if source.x < target.x: #linke Seite
source.right = target.left
print("links")
else:
source.left = target.right
#print("rechts")
Here is the place from where I call my function:
class Map :
def __init__(self,game, x, y):
self.game = game #stellt Bezug zum Spiel
#self.tako_chan = Tako_Chan(self,x,y)
self.x = x #wird in unteren Methode () verwendet
self.y = y #wird in unteren Methode () verwendet
self.map_01 = pygame.image.load("map_01.PNG")
self.map_02 = pygame.image.load("map_02.PNG")
self.warp_point = pygame.Rect(630, 620, 150,80 ) #x y width height
self.warp_point_2 = pygame.Rect(500, -70, 150, 80) # x y width height
self.palm_rec = pygame.Rect(450, 300, 60, 150) # x y width height
def update (self):
if self.game.location == "01":
self.game.screen.blit(self.map_01, (self.x, self.y)) # Bild/Position Vorgänger
pygame.draw.rect(self.game.screen, (0, 255, 0), self.warp_point, 4)
pygame.draw.rect(self.game.screen, (150, 200, 0), self.palm_rec, 5)
self.game.snake.move_horizon()
self.game.snake.update()
if self.game.tako_chan.tako_chan_rect.colliderect(self.palm_rec):
None
collision (self.game.tako_chan.tako_chan_rect, self.palm_rec)