[英]I have created hitboxes for my flappy dragon but the hitboxes are either not colliding or doesn't produce an output. How do i fix that?
我正在嘗試為我的 Python 編程課程制作一個flappybird 游戲,並且我使用了諸如 drag.hit() 之類的提示,這會導致它們在每次碰撞盒碰撞時打印(“hit”)。 但是,dragon 和 stumpy hitbox 的碰撞不起作用,我似乎無法讓它起作用。
這是我的代碼:
pygame.init()
class player(object): **class for dragon**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 5, self.y +3, 67, 65)
def draw(self,win): **drawing of hitbox for dragon**
self.hitbox = (self.x + 5, self.y +3, 67, 65)
pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
def hit(self): **During collision of hitbox, print hit**
print("hit")
class stumpy(object): **class for obstacle 1**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-15)
def draw(self, win):
win.blit(pygame.transform.scale(self.walkLeft[self.count//3], (75, 200)), (self.x, self.y)) #fx to scale up or down object. transform, dimension, placement
pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2) #arguments - window, colour, dimension, thickness
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-15) #x-start, y-start, length, breath
class stumper(object): **class for obstacle 2**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-20)
def draw(self,win):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-20)
pygame.draw.rect(win, (255,0,0), self.hitbox, 2)
win.blit(pygame.transform.scale(self.walkLeft[self.count//1], (75,200)), (self.x,self.y))
def redrawGameWindow():
global walkCount
win.blit(bg, (bgX,0)) # This will draw our background image at (0,0)
win.blit(bg, (bgX2,0)) # This will draw our background image at (1024,0)
drag.draw(win)
for obstacle in obstacles:
obstacle.draw(win)
pygame.display.update()
speed = 30 **assign variable for fps**
drag = player(95, 396//2, 75, 73) #class for dragon, unnecessary
stump = stumpy(810, 310, 75, 200) #class for stump, unnecessary
Istump = stumper(810, -20, 75, 200)
obstacles= []
#main loop
run = True
while run:
redrawGameWindow()
pygame.time.delay(25)
for obstacle in obstacles:
if drag.hitbox[1] < Istump.hitbox[1] + Istump.hitbox[3] and drag.hitbox[1] + drag.hitbox[3] > stump.hitbox[1]: #must create player instance for this to work so using class is useless
if drag.hitbox[0] + drag.hitbox[2] > Istump.hitbox[0] and drag.hitbox[0] < Istump.hitbox[0] + Istump.hitbox[2]:
if drag.hitbox[0] + drag.hitbox[2] > stump.hitbox[0] and drag.hitbox[0] < stump.hitbox[0] + stump.hitbox[2]:
drag.hit()
obstacles.append(stumpy(250, 250, 100, 100))
redrawGameWindow()
pygame.quit()
在您的播放器類中,將 pygame rect 用於您的hitbox:
self.hitbox = pygame.Rect(self.x + 5, self.y +3, 67, 65)
然后對你的對象做同樣的事情,這樣玩家和障礙物都是 pygame.Rect 對象。 要檢測玩家是否在障礙物中,您只需使用:
if player.hitbox.colliderect(obstacle.hitbox):
print('hit')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.