【问题标题】:Gravity and Collision with Walls - PYGAME重力和与墙壁的碰撞 - PYGAME
【发布时间】:2022-03-03 06:42:22
【问题描述】:

当玩家与墙发生碰撞时,它会跳到墙的顶部。该方法在与地板障碍物碰撞时效果很好。但我不明白为什么与墙壁的碰撞会降低我的 player.rect.y 坐标。

class player_jump:
 def __init__(self):
    self.jump = False
    self.in_aire = True
    self.vel_y = 0

 def move_y(self):
        #reset movment variables
        dy = 0

        if self.jump and not self.in_air:
            self.vel_y = -11
            self.jump = False
            self.in_air = True

        #apply gravity (global variable , GRAVITY = 0.5 )
        self.vel_y += GRAVITY
        if self.vel_y > 10:
            self.vel_y = 0
   
        dy += self.vel_y

        #check for collision (world.obstacle_list - contain data on wall and bottom rects)
        for tile in world.obstacle_list:
            #x direction
            if tile[1].colliderect(self.rect.x + dx,self.rect.y,self.rect.width,self.rect.height):
                dx = 0
              
            #y direction
            if tile[1].colliderect(self.rect.x,self.rect.y + dy,self.rect.width,self.rect.height):
                #check if below the ground , i.e jumping
                if self.vel_y < 0:
                    self.vel_y = 0
                    dy = tile[1].bottom - self.rect.top
                    self.in_air = False
                #check if above the ground i.e falling
                elif self.vel_y >= 0:
                    self.in_air = False
                    dy = tile[1].top - self.rect.bottom
                    
        # update rectangle position
        self.rect.x += dx
        self.rect.y += dy

【问题讨论】:

  • 你为什么用self.img.get_width()而不是self.rect.widthheight一样?
  • 其他图块是否自行移动?就像在某些时候玩家本身并没有改变它的坐标但是所有的瓷砖都改变了它们的位置一样?因为您可能也需要考虑这一点
  • @Matiiss 将其修复为 self.rect.width 和 height。瓷砖确实改变了它们的位置。当他们不 - 它不会发生。但还是不明白为什么。

标签: python pygame


【解决方案1】:

您的算法取决于图块的顺序。使算法顺序独立于沿轴的碰撞检测。

首先对所有图块沿 x 轴运行碰撞检查。然后沿 y 轴对所有图块运行碰撞检查。沿 y 轴运行测试时,您还需要考虑沿 x 轴的移动:

# x direction
test_rect = self.rect.move(dx, 0)
for tile in world.obstacle_list:
    if tile[1].colliderect(test_rect):
        dx = 0
        break
              
# y direction
for tile in world.obstacle_list:
            
    test_rect = self.rect.move(dx, dy)
    if tile[1].colliderect(test_rect):
        # [...]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多