1

我目前正在研究 pygame 的抽象层,并且在尝试检查与地图的碰撞时遇到了问题。我能够加载和显示地图,以及存储可碰撞的矩形。当我打印矩形列表时,我看到一切都准备好了,但是当我遍历每个矩形并尝试检查与另一个矩形的碰撞时,即使矩形没有碰撞,它也总是返回 true。此外,当我尝试通过在每个矩形上绘制一个红色轮廓的矩形来调试所有矩形时,即使在我打印矩形时,它也不会绘制任何内容,它会打印一个存在的矩形。

以下是框架中的一些片段:

class Tilemap(object):
"""This is the tilemap object, it takes an array of strings as its object, and places a surface where you have it in the strings. It only supports one surface per map, so you have to make multiple maps for floor, walls, etc."""
def __init__(self, level_surface,level_string = None, string_char = "#", surface = None, surface_dim = Vector2(50, 50),surface_color = (255, 255, 255)):
    self.level = level_string
    self.char = string_char
    self.surface = surface
    if self.surface is None:
        self.surface = pygame.Surface(surface_dim)
        self.surface.fill(surface_color)

    self.surface_width = self.surface.get_rect().w
    self.surface_height = self.surface.get_rect().h
    self.collision_list = []
    for y in xrange(len(self.level)):
        for x in xrange(len(self.level[y])):
            if self.level[y][x] is self.char:
                self.collision_list.insert(len(self.collision_list), Rect((x) * self.surface_width,(y) * self.surface_height, self.surface_width, self.surface_height))
    print self.collision_list
    for y in xrange(len(self.level)):
        for x in xrange(len(self.level[y])):
            if self.level[y][x] is self.char:
                level_surface.blit(self.surface.convert_alpha(), (self.surface_width * x, self.surface_height * y))

def replace_char_with(self, level_surface,char = ".", surface = None):
    for y in xrange(len(self.level)):
        for x in xrange(len(self.level[y])):
            if self.level[y][x] is char:
                level_surface.blit(surface.convert_alpha(), (surface.get_width() * x, surface.get_height() * y))

def check_col(self, rect):
    for tilerect in self.collision_list:
        if rect.x + rect.w > tilerect.x or rect.y + rect.h > tilerect.y or rect.x < tilerect.x + tilerect.w or rect.y < tilerect.y + tilerect.h:
            return True
        else:
            return False

def debug_draw(self, screen):
    for rect in self.collision_list:
        pygame.draw.rect(screen, (255, 0, 0), rect, 2)

片段#2,测试代码:

def main():
from pygame.locals import K_w, K_a, K_s, K_d
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
player = Sprite(pygame.image.load("trapdoor_tile.png"), Vector2(100, 100))
floor = ["########################################",
         "########################################",
         "#####...##.#.#..###.#.###..#############",
         "#####.######.#.#.####.##.#.#############",
         "######.###.#.##..##.#.###.##############",
         "#####.####.########.####################",
         "#####.#.##.###.#.##.#.##.#.#############",
         "########################################",
         "#######################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################"
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################",
         "########################################"]

walls = ["########################################",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "#......................................#",
         "########################################"]

level_surf = pygame.Surface((640, 480))
floor_map = Tilemap(level_surf, floor, "#", pygame.image.load("ground_tile.png").convert_alpha())
floor_map.replace_char_with(level_surf, ".", pygame.image.load("trapdoor_tile.png").convert_alpha())
wall_map = Tilemap(level_surf, walls, "#", pygame.image.load("wall_tile.png").convert_alpha())

while True:
    screen.fill((0, 0, 0))
    milliseconds = clock.tick(60) / 10.

    for event in pygame.event.get():
        if event.type == pygame.locals.QUIT:
            pygame.quit()
            raise SystemExit

    wall_map.debug_draw(screen);

    screen.blit(level_surf, Vector2(0, 0))

    if wall_map.check_col(player.dummyrect):
        player.colliding = True
        print "why!"
    else:
        player.colliding = False

    player.update(milliseconds)
    player.draw(screen)

    keystate = pygame.key.get_pressed()

    player.apply_drag()

    if keystate[K_w]:
        player.set_accel_y(-5)
    elif keystate[K_s]:
        player.set_accel_y(5)
    elif keystate[K_a]:
        player.set_accel_x(-5)
    elif keystate[K_d]:
        player.set_accel_x(5)

    pygame.display.flip()

创建玩家的精灵类:

class Sprite(object):
def __init__(self, surface = None, initial_position = (100, 100)):
    self.surface = surface
    self.rect = self.surface.get_rect(center = initial_position)
    self.acceleration = Vector2(0, 0)
    self.delta_time = None
    self.dummyrect = self.rect
    self.colliding = False

def update(self, delta_time):
    self.dummyrect = self.rect.move(self.acceleration.x * delta_time, self.acceleration.y * delta_time)
    if not self.colliding:
        self.rect = self.dummyrect
    else:
        self.dummyrect = self.rect
    self.delta_time = delta_time

def draw(self, screen):
    screen.blit(self.surface, self.rect)

def draw_to_cam(self, screen,camera):
    screen.blit(self.surface, camera.to_camera_coords(Vector2(self.rect.x, self.rect.y)))

def collide(self, rectangle):
    if self.rect.x + self.rect.w > rectangle.x:
        self.rect.x -= 1;
    if self.rect.x < rectangle.x + rectangle.w:
        self.rect.x += 1
    if self.rect.y < rectangle.y + rectangle.h:
        self.rect.y += 1;
    if self.rect.y + self.rect.h > rectangle.y:
        self.rect.y -= 1;

def set_accel_x(self, new_val):
    self.acceleration.x = new_val

def set_accel_y(self, new_val):
    self.acceleration.y = new_val

def apply_drag(self, drag_mul = 1):
    if self.acceleration.x > 0:
        self.acceleration.x -= self.delta_time * drag_mul
    else:
        self.acceleration.x += self.delta_time * drag_mul

    if self.acceleration.y > 0:
        self.acceleration.y -= self.delta_time * drag_mul
    else:
        self.acceleration.y += self.delta_time * drag_mul

    if self.acceleration.x < 0.1 or self.acceleration.x > -0.1:
        self.acceleration.x = 0
    if self.acceleration.x < 0.1 or self.acceleration.x > -0.1:
        self.acceleration.x = 0
    if self.acceleration.y < 0.1 or self.acceleration.y > -0.1:
        self.acceleration.y = 0
    if self.acceleration.y < 0.1 or self.acceleration.y > -0.1:
        self.acceleration.y = 0

def get_center(self):
    return Vector2(self.rect.centerx, self.rect.centery)

这些是涉及的三个主要片段,我不知道为什么每次都会返回碰撞,但似乎确实如此。如果有人有答案,或者至少解释一下为什么会发生这种情况,请帮助兄弟!

4

2 回答 2

1

你需要一些and's 在你的碰撞检查。

例如:

def check_col(self, rect):
    for tilerect in self.collision_list:
        collide_x = False
        collide_y = False
        # check x axis for collision
        if self.rect.x + self.rect.w > tilerect.x:
            collide_x = True
        elif self.rect.x < tilerect.x + tilerect.w:
            collide_x = True
        # check y axis for collision
        if self.rect.y < tilerect.y + tilerect.h:
            collide_y = True
        elif self.rect.y + self.rect.h > tilerect.y:
            collide_y = True
        # act on a collision on both axis
        if collide_x and collide_y:
            return True
        else:
            return False
于 2013-04-09T01:05:51.733 回答
1

您的 check_col 函数使用所有“或”运算符,这意味着只要满足一个条件,您就会为碰撞返回 true。这是您的代码:

def check_col(self, rect):
for tilerect in self.collision_list:
    if rect.x + rect.w > tilerect.x or rect.y + rect.h > tilerect.y or rect.x < tilerect.x + tilerect.w or rect.y < tilerect.y + tilerect.h:
        return True
    else:
        return False

你想要的是更像这样的东西:

def check_col(self, rect):
    for tilerect in self.collision_list:
        if ((rect.x + rect.w > tilerect.x and rect.x <= tilerect.x + tilerect.width) or
            (tilerect.x + tilerect.width > rect.x and tilerect.x <= rect.x + rect.width)) and
            ((rect.y + rect.h > tilerect.y and rect.y <= tilerect.y + tilerect.height) or
            (tilerect.y + tilerect.height > rect.y and tilerect.y <= rect.y + rect.height))

            return true
        else:
            return false

此外,值得指出的是,pygame 的 Rect 类有自己的一组碰撞检测函数。要检测 2 个矩形之间的碰撞,您可以使用 rect.colliderect(Rect)。

http://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect

于 2013-04-09T17:12:25.690 回答