在我正在涉足的平台游戏中,我遇到一个问题,即玩家控制的单位会短暂停止然后继续下降。
简要描述 - 处于下降状态的单位在下降时加速。我使用它的当前速度来确定它是否会与给定的物体碰撞。
我期望它采取行动的方式处于自由落体状态(下降状态),pg.sprite.spritecollideany将返回false,直到它击中某个东西(或者预计会击中某些东西)。在那一点上,它总会击中某些东西,从而返回是,不再下降。
实际发生的事情是,一旦发生碰撞,单位会暂时停止,但随后会返回其下降状态,直到碰到其他东西并重复此过程。
我真的不知道为什么会发生这种情况
这是相关代码。我认为重要的代码是up_down_collision函数
class Unit(pg.sprite.Sprite):
def create_self_rect(self):
self.rect = pg.Rect(50, 50, 10, 20)
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.x = 100
self.y = 100
self.y_vel = 0
self.x_vel = 0
self.jumping_velocity = 3
self.gravity = .1
self.jumped = 0
self.state = {}
self.state['jumping'] = False
self.state['falling'] = True
self.state['grounded'] = False
self.create_self_rect()
def update_rect(self):
self.rect = pg.Rect(self.x, self.y, 10, 20)
def change_state(self, new_state):
for state in self.state:
self.state[state] = False
self.state[new_state] = True
def return_state(self):
for state in self.state:
if self.state[state]:
return state
def update(self):
self.left_right_collision(worlds.all_obstacles, self.x_vel) #worlds is a seperate module that holds all the collidables. nothing special
self.up_down_collision(worlds.all_obstacles, self.y_vel)
if self.return_state() is 'falling':
self.falling_state()
if self.return_state() is 'grounded':
self.y_vel = 0
self.update_position()
self.update_rect()
def update_position(self):
self.x += self.x_vel
self.y += self.y_vel
def falling_state(self):
time = pg.time.get_ticks()
self.y_vel = self.y_vel + \
(((time - self.jumped) / 1000) * self.gravity)
def up_down_collision(self, collidables, velocity):
self.rect.move_ip(0, velocity)
if pg.sprite.spritecollideany(self, collidables):
collidables = pg.sprite.spritecollide(self, collidables, False)
for platform in collidables:
if abs(velocity) == velocity:
self.rect.move_ip(0, -velocity)
self.rect.bottom = platform.rect.top
self.change_state('grounded')
else:
self.rect.move_ip(0, -velocity)
self.rect.top = platform.rect.bottom
self.y_vel = 0
else:
self.change_state('falling')
class Platform(pg.sprite.Sprite):
def __init__(self, start_pos, size): #startpos, size are tuples
pg.sprite.Sprite.__init__(self)
self.x = start_pos[0]
self.y = start_pos[1]
self.width = size[0]
self.height = size[1]
self.rect = pg.Rect(self.x, self.y, self.width, self.height)
pg.draw.rect(game_screen, (200, 200, 200), player.rect)
lp = pf.Platform((300, 800), (500, 10))
pg.draw.rect(game_screen, (200, 200, 200), lp.rect)
hp = pf.Platform((800, 700), (200, 10))
pg.draw.rect(game_screen, (200, 200, 200), hp)
base = pf.Platform((0, 900), (1680, 200))
pg.draw.rect(game_screen, (200, 200, 200), base)
wall = pf.Platform((1500, 700), (50, 300))
pg.draw.rect(game_screen, (200, 200, 200), wall)
worlds.all_obstacles = [lp, hp, base, wall]
也请原谅可怜的代码。发帖真是太尴尬了!
答案 0 :(得分:1)
update
:
if self.return_state() is 'falling':
# ^ should be == not is
您正在测试身份,而不是等效。