简体   繁体   中英

Wall sprite not showing up on screen after certain coordinates in pygame

Trying to make collision detection as means to make sprites bounce off one another, but my wall sprites aren't showing up after coords (5, 5) I wasn't sure if maybe it had to do with fill and colorkey both being white, or the fact that pygame.Surface(x, y) is the same as the x, y for the rect.

Here's my wall class:

class Wall(pygame.sprite.Sprite):

def __init__(self, color, h, d, x, y):
    super().__init__()

    self.image = pygame.Surface([x, y])
    self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)

    pygame.draw.rect(self.image, color, [h, d, x, y])

    self.rect = self.image.get_rect()

and here's my code for my call to create wall 3 an wall 4:

wall3 = Wall(BLACK, 0, 400, 700, 2)
wall_list.add(wall3)
all_sprite_list.add(wall3)

wall4 = Wall(BLACK, 700, 0, 2, 400)
wall_list.add(wall4)
all_sprite_list.add(wall4)

As for me you have two problems

First: you use missleading names - variables x,y should be rather width, height but this later.

Second: you assume that surface uses the same coordinates as screen but it not true. It starts at (0,0) and ends in your (x,y) but you try to draw rect in position (h,d) which is outside surface.

So in line

pygame.draw.rect(self.image, color, [h, d, x, y])

you need (0,0) instead of (h,d)

pygame.draw.rect(self.image, color, [0, 0, x, y])

and you have to use (h,d) with Rect()

self.rect = self.image.get_rect()
self.rect.x = h
self.rect.y = d

Frankly, draw.rect() will use all surface so you could do the same using only fill()

def __init__(self, color, h, d, x, y):
    super().__init__()

    self.image = pygame.Surface([x, y])
    self.image.fill(color)

    self.rect = self.image.get_rect()
    self.rect.x = h
    self.rect.y = d

If you use better names for variables then you get

def __init__(self, color, x, y, width, height):
    super().__init__()

    self.image = pygame.Surface([width, height])
    self.image.fill(color)

    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM