0
在我參與的一些平臺遊戲中,我遇到了一個問題,玩家控制的單元暫時停下來,然後繼續下降。pygame.sprite.spritecollideany沒有碰撞?
簡要說明 - 處於墜落狀態的單位在墜落時會加速。我使用它的當前速度來確定它是否會與給定對象發生碰撞。
我認爲這樣做的方式是處於自由下落狀態(下降狀態),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]
也請原諒糟糕的代碼。發佈很令人尷尬!
對不起!更新了代碼以顯示返回狀態。即使我做出你所建議的改變,該單位仍然下降。如果您需要更多信息,請讓我知道!它的一切有點kludgey和im有點尷尬顯示更多! –
你有沒有放入任何'印刷品'來確定狀態?單獨測試程序的某些部分? – jonrsharpe