2012-03-30 53 views
0

我有一個字符(其((x,y)位置存儲在bodyc中)和一堆平臺。這些平臺以變量「plist」表示,並以時尚[[x,y],pygame.Surface實例]存儲。角色以速度跳躍。(Python)平臺遊戲 - 字符跳過/錯誤放置

這是我目前的算法:

def onplatform(self): 
    for i in plist: 
     if intersect(i[0]+list(i[1].get_size()), [bodyc[0], bodyc[1], 50, 50]): 
      return True, plist.index(i) 
     return False, len(plist) 

onplat=self.onplatform() 
if yvelocity!=-13: 
    bodyc[1]-=yvelocity 
if yvelocity>-12: yvelocity-=1 
if yvelocity==-13 and not onplat[0]: yvelocity=-1 
if onplat[0] and -13<yvelocity<-1: 
    yvelocity=-13 
    bodyc[1]=plist[onplat[1]][0][1]-50 #(y-value of platform)-50 
if pressed[pygame.K_UP] and yvelocity==-13: 
    yvelocity=13 

這個算法的問題是,當該角色是觸摸平臺,即使底部是不是在平臺上,該代碼就會把字符到反正平臺。

我試過讓它變得非常小(1或3像素高),但角色並沒有觸及平臺,因爲速度會讓角色跳過平臺。將其設置得更大,如5或7像素,具有與上述相同的問題。

有沒有簡單的方法來解決這個問題?

回答

1

我發現答案(它實際上需要大約20分鐘)。

prevcoords是以前座標bodyc,精靈的座標,yvelocity是字符的y-速度。

對於那些也陷入「平臺化問題」的未來程序員:如果你想製作一個多屏平臺遊戲,你將不得不修改這個程序,因爲這樣做效率很低。此外,這可能不適用於不對稱的精靈。

def intersect(recta, rectb): 
    a=(rectb[1]+rectb[3]<recta[1]) or (recta[1]+recta[3]<rectb[1]) #up, down 
    b=(rectb[0]+rectb[2]<recta[0]) or (recta[0]+recta[2]<rectb[0]) #left, right 
return not(a or b) 

def onplatform(self): 
    for i in plist: 
     if intersect(i[0]+[i[1].get_width(), 1], [bodyc[0], bodyc[1]+47, 50, 3]): 
      return True, plist.index(i) 

onplat=self.onplatform() 
if yvelocity!=-13: 
    bodyc[1]-=yvelocity 
    for i in plist: 
     temp=i[0][0]<bodyc[0]+50<i[0][0]+i[1].get_width() 
     temp2=i[0][0]<bodyc[0]<i[0][0]+i[1].get_width() 
     if prevcoords[1]+50<=i[0][1]<=bodyc[1]+50 and (temp or temp2): 
      bodyc[1]=i[0][1]-50 
      yvelocity=-13 
      break 
if yvelocity>-12: yvelocity-=1 
if yvelocity==-13 and not onplat[0]: yvelocity=-1 
if pressed[pygame.K_UP] and yvelocity==-13: 
    yvelocity=13 
prevcoords=bodyc[:]