重力和与墙壁的碰撞 - PYGAME
Gravity and Collision with Walls - PYGAME
当玩家与墙碰撞时,它会跳到墙顶。该方法在与地板障碍物碰撞时效果很好。但我不明白为什么与墙壁的碰撞会降低我的 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
您的算法取决于图块的顺序。使算法顺序独立于沿轴的碰撞检测。
首先 运行 沿 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):
# [...]
当玩家与墙碰撞时,它会跳到墙顶。该方法在与地板障碍物碰撞时效果很好。但我不明白为什么与墙壁的碰撞会降低我的 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
您的算法取决于图块的顺序。使算法顺序独立于沿轴的碰撞检测。
首先 运行 沿 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):
# [...]