0

I'm making a dungeon game. I started to implement collision. It's a simple rectangular collision detection. But I don't know how to do this. I want to collide obstacle objects with the player

I have X and Y position of all objects, and X border and Y border position of objects.

import pygame
from pygame.locals import *
screen = pygame.display.set_mode((500, 500))
ball = pygame.image.load("ball.png") #43x43 png
white = (255, 255, 255)
black = (0, 0, 0)
px = 0
py = 0
ticker = 0
class obstacle(object):
    def __init__(self, x, y, xbord, ybord):
        self.x = x
        self.y = y
        self.xbord = xbord
        self.ybord = ybord
        self.surf = pygame.Surface((self.xbord, self.ybord))
        self.surf.fill(black)
o = []
o.append(obstacle(50, 50, 70, 58))
while True:
    keys = pygame.key.get_pressed()
    screen.fill(white)
    for obstacle in o:
        screen.blit(obstacle.surf, (obstacle.x, obstacle.y))
        pass
        #code to check which way the player is touching an obstacle and deny walking into the obstacle
    if ticker == 0:
        if keys[K_UP]:
            py -= 1
        if keys[K_DOWN]:
            py += 1
        if keys[K_RIGHT]:
            px += 1
        if keys[K_LEFT]:
            px -= 1
        ticker = 15
    if ticker > 0:
        ticker -= 1
    screen.blit(ball, (px, py))
    pygame.event.get()
    pygame.display.flip()
markop
  • 75
  • 3
  • 11
  • Here's an answer in which I explain how to do this: https://stackoverflow.com/a/45017561/6220679 – skrx Apr 07 '18 at 14:14

1 Answers1

0

You can use the pygame.Rect.colliderect(). I will apply it in the obstacle class.

class obstacle(object):  # Your class code
    def __init__(self, x, y, xbord, ybord):
        self.x = x
        self.y = y
        self.xbord = xbord
        self.ybord = ybord
        self.surf = pygame.Surface((self.xbord, self.ybord))
        self.surf.fill(black)

    def collide_ball(self):
        if self.surf.get_rect().colliderect(ball.get_rect()):
            return True
.... # Other code

while True:
    for obstacle in o:
        if obstacle.collide_ball():
              pass # Your statements (What you want to do when the obstacle collide with the surface of the ball
Ethanol
  • 370
  • 6
  • 18