Python 获得正确的玩家碰撞
我正在用pygame制作一个基于瓷砖的plaformer游戏。这是我的玩家精灵: 这是碰撞检测器代码:Python 获得正确的玩家碰撞,python,python-3.x,pygame,Python,Python 3.x,Pygame,我正在用pygame制作一个基于瓷砖的plaformer游戏。这是我的玩家精灵: 这是碰撞检测器代码: for tile in world.tile_list: # check for collision in x direction if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height): dx = 0
for tile in world.tile_list:
# check for collision in x direction
if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
dx = 0
# check for collision in y direction
if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
# check if below the ground i.e. jumping
if self.vel_y < 0:
dy = tile[1].bottom - self.rect.top
self.vel_y = 0
# check if above the ground i.e. falling
elif self.vel_y >= 0:
dy = tile[1].top - self.rect.bottom
self.vel_y = 0
用于world.tile\u列表中的互动程序:
#检查x方向的碰撞
如果平铺[1]。碰撞矩形(self.rect.x+dx,self.rect.y,self.width,self.height):
dx=0
#检查y方向是否有碰撞
如果平铺[1].colliderect(self.rect.x,self.rect.y+dy,self.width,self.height):
#检查是否在地面以下,即跳跃
如果self.vel_y<0:
dy=平铺[1]。底部-self.rect.top
self.vel_y=0
#检查是否高于地面,即是否坠落
elif self.vel_y>=0:
dy=平铺[1]。顶部-self.rect.bottom
self.vel_y=0
当我运行游戏时,如图所示:玩家可以站在平台外,
我需要得到正确的玩家宽度,所以当我使用
我可以手动将宽度指定为从第一条腿到第二条腿的宽度,但是当我这样做时,碰撞检测器检测到图像中间的宽度,并且没有正确对齐它,因此没有自动解决方案。您需要为碰撞测试定义一个子区域:
offset_x=#offset_x是到“黑色”像素的第一个距离
脚部宽度=#脚部宽度
foot_x=自校正x+偏移量_x
对于world.tile\u列表中的tile:
#检查x方向的碰撞
如果平铺[1]。碰撞矩形(self.rect.x+dx,self.rect.y,self.width,self.height):
dx=0
#检查y方向是否有碰撞
#检查是否在地面以下,即跳跃
如果self.vel_y<0:
如果平铺[1].colliderect(self.rect.x,self.rect.y+dy,self.width,self.height):
dy=平铺[1]。底部-self.rect.top
self.vel_y=0
#检查是否高于地面,即是否坠落
如果self.vel_y>=0:
如果平铺[1].colliderect(英尺x,自.rect.y+dy,英尺宽度,自.height):
dy=平铺[1]。顶部-self.rect.bottom
self.vel_y=0
谢谢,在碰撞测试中,我必须在哪里使用foot\u x
和foot\u width
变量?@Make错误请阅读我的答案。最后第三行:if tile[1]。collide rect(foot\u x,self.rect.y+dy,foot\u width,self.height):
@rabbit噢对不起