Python Forum
[PyGame] Creating Map Obstacles
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Creating Map Obstacles
#4
You need to move collision out of moving. Then handle it after sprite has been moved.
Right now it collides and never told how to get uncollided. So once collided it stuck forever.
Collision could be solve in two ways. When collided move back to old position or displace sprite.

The up, down, left, and right variables aren't needed.

Fence locations should be outside of main loop.
    # Fence Rectangles
    fence = [
        pygame.draw.rect(screen, red, pygame.Rect(455, 65, 20, 85)),
        pygame.draw.rect(screen, red, pygame.Rect(390, 65, 85, 20)),
        pygame.draw.rect(screen, red, pygame.Rect(390, 0, 20, 85)),
        pygame.draw.rect(screen, red, pygame.Rect(395, 0, 240, 20)),
        pygame.draw.rect(screen, red, pygame.Rect(615, 0, 20, 150)),
        pygame.draw.rect(screen, red, pygame.Rect(580, 130, 40, 20)),
        pygame.draw.rect(screen, red, pygame.Rect(455, 130, 80, 20))
    ]
outside of main loop. Build sequence once.
fences = (
    pygame.Rect(455, 65, 20, 85),
    pygame.Rect(390, 65, 85, 20),
    pygame.Rect(390, 0, 20, 85),
    pygame.Rect(395, 0, 240, 20),
    pygame.Rect(615, 0, 20, 150),
    pygame.Rect(580, 130, 40, 20),
    pygame.Rect(455, 130, 80, 20))
Fence draw code
for fence in fences:
    pygame.draw.rect(screen, pygame.Color('red'), fence)
You can also look into pygame.Vector2 or just use pygame.Rect for player movement.
char = pygame.Rect(507, 60, 25, 40)
# mainloop
moved = None
if pressed[pygame.K_UP] and not press[pygame.K_DOWN]:
    moved = char.move(0, -3)
# ...

# if no collision allow movement
if moved:
    if moved.collidelist(fences) == -1:
        char = moved
99 percent of computer problems exists between chair and keyboard.
Reply


Messages In This Thread
Creating Map Obstacles - by cameron121901 - Jun-05-2019, 08:00 PM
RE: Creating Map Obstacles - by metulburr - Jun-05-2019, 08:40 PM
RE: Creating Map Obstacles - by cameron121901 - Jun-06-2019, 06:09 AM
RE: Creating Map Obstacles - by Windspar - Jun-06-2019, 11:06 AM
RE: Creating Map Obstacles - by cameron121901 - Jun-06-2019, 07:42 PM
RE: Creating Map Obstacles - by Windspar - Jun-06-2019, 08:45 PM
RE: Creating Map Obstacles - by cameron121901 - Jun-07-2019, 06:08 PM
RE: Creating Map Obstacles - by Windspar - Jun-07-2019, 07:53 PM
RE: Creating Map Obstacles - by cameron121901 - Jun-10-2019, 03:56 PM
RE: Creating Map Obstacles - by Windspar - Jun-10-2019, 05:43 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020