【问题标题】:Why wont my collision detection or falling images work?为什么我的碰撞检测或坠落图像不起作用?
【发布时间】:2019-04-20 22:41:40
【问题描述】:

我最近编写了这段代码,其中水果和其他东西从屏幕顶部掉下来,底部的青蛙必须尝试抓住它们。碰撞检测不起作用,掉落的图像也不起作用,因为它们似乎只是掉落并卡在屏幕顶部。这是我的大部分代码,因为我似乎无法确定实际错误在哪个区域:

import pygame, sys, time, random
from pygame.locals import *
######### constants ##########
jumpvel=20
fallingspeed=0.5
running= True
blue= [129,183 ,253]
pink=[255,174,201]
textcolour= [255,255,255]
x=700//2
y=1000//2

score=0

#### fruits and naughty ######
thingylist= ['fruit1.bmp','fruit2.bmp','fruit3.bmp','fruit4.bmp','fruit5.bmp','fruit1.bmp','fruit2.bmp','fruit3.bmp','fruit4.bmp','fruit5.bmp','naughty1.bmp','naughty2.bmp','naughty3.bmp',]
all_things=[]
for i in range (12):
    new_thing_image=pygame.image.load(thingylist[(random.randrange(0,12))])
    new_thing_image.set_colorkey(pink)
    new_thing_rect=new_thing_image.get_rect()
    new_thing_rect.x=random.randrange(0,950)
    new_thing_rect.y=-random.randrange(50,500)
    all_things.append([new_thing_image,new_thing_rect])


################collision###############
def checkCollision (frog_rect,all_things,score):
    collides_with=None
    for i in range (len(all_things)):
        thing_rect=all_things[i][1]
        if (frog_rect.colliderect(thing_rect)):
            score=score+100
    return collides_with



######## initialising screen#########        
pygame.init()
gamedisplay=pygame.display.set_mode((1000,600)) #making the screen
pygame.display.set_caption('frog')
clock=pygame.time.Clock()# frames per second
bg=pygame.image.load('actual clouds.bmp').convert()


############ initialising sprites##############
frog= pygame.image.load('actual frog.bmp')
frog.set_colorkey(blue)
frog_rect=frog.get_rect()
frog_rect.centerx=(x)
frog_rect.centery=(y)


####### score###########
pygame.font.init()
font= pygame.font.SysFont ('Dubai MS', 48)

##########drawing things#############
def drawThings (all_things):
    for item in all_things:
        new_thing_image, new_thing_rect= item
        gamedisplay.blit(new_thing_image, (new_thing_rect.x, new_thing_rect.y))



#########update display function###########
def update(x,y,all_things,score):
    gamedisplay.blit(bg,[0,0])
    gamedisplay.blit(frog,(x,y))
    for thing in range (len(all_things)):
        new_thing_rect=all_things[i][1]
        #thing_rect.y=thing_rect.y+fallingspeed
        new_thing_rect.y+= fallingspeed
    drawThings(all_things)
    label=font.render("score "+ str(score) ,1,textcolour)
    gamedisplay.blit(label,(750,10))
    pygame.display.update()
    pygame.time.delay(50)



#########main game loop ############
while running == True:
    gamedisplay.blit(bg,[0,0])
    gamedisplay.blit(frog,(x,y))
    drawThings(all_things)
    label=font.render("score "+ str(score) ,1,textcolour)
    gamedisplay.blit(label,(750,10))
    pygame.display.flip()
    pygame.event.pump()
    key=pygame.key.get_pressed()

    ########### escape ###########
    if key [pygame.K_ESCAPE]:
        sys.exit()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    ########### controls ##############        
    if key[pygame.K_LEFT]:
        x -=2

    elif key[pygame.K_RIGHT]:
        x +=2

    elif key[pygame.K_SPACE]or key[pygame.K_UP]:
        for i in range (5):
            y -= jumpvel
            update(x,y,all_things,score)
        for i in range (5):
            y += jumpvel
            update(x,y,all_things,score)
    ######## limits ####################
    if x < 10:
        x = 10
    elif (x > (900 - 2)):
        x= 900-2

    ######### falling###########

    for item in all_things:
        new_thing_image, new_thing_rect= item
        #new_thing_rect=all_things[i][1]
        #thing_rect.y=thing_rect.y+fallingspeed
        new_thing_rect.y+= fallingspeed

    ############collision detection##########
    detect=checkCollision (frog_rect, all_things,score)
    if (detect !=None):
        score=score+100

update(x,y,all_things,score)

“东西”本来是要掉到屏幕底部让青蛙抓的,但它们似乎都卡在了顶部。当我测试碰撞检测代码时,即使两个图像发生碰撞,它对分数也没有影响——这意味着某些东西不起作用。

【问题讨论】:

    标签: python pygame collision-detection rect


    【解决方案1】:

    因为这个原因,下落的图像停止了

    fallingspeed = 0.5
    

    rect 使用整数值来保持位置,因此它将0.5 舍入为整数 - int(0.5) == 0

    当你有y = 0 并添加0.5 - 所以你可以期待y = 0.5 - 它会将它四舍五入到y = 0。在下一个循环中,您将再次添加 0.5 并将其再次舍入为 y = 0。这样它就停在y = 0

    当你有 y = -5 并添加 0.5 时,你可以期待 -4.5 但它会四舍五入到 -4(不是 -5)所以它正在移动。

    使用

    fallingspeed = 1
    

    它不会停止在y = 0


    old_y = 0
    new_y = int(old_y+0.5)
    print(old_y, new_y) 
    
    # 0 0
    
    old_y = -5
    new_y = int(old_y+0.5)
    print(old_y, new_y) 
    
    # -5 -4
    

    有时在更复杂的代码中,将位置保持在浮点值中很重要,然后您必须使用float 变量而不是rect 来保持位置并将其复制到rect,仅当您必须绘制或检查碰撞


    碰撞

    checkCollision 内部,您设置了 collides_with = None,但您从未将其更改为 `True

     def checkCollision (frog_rect,all_things, score):
         collides_with = None
    
         for i in range (len(all_things)):
             thing_rect = all_things[i][1]
             if (frog_rect.colliderect(thing_rect)):
                  score=score+100
                  collides_with = True
    
         return collides_with
    

    你可以写得更短

     def checkCollision(frog_rect,all_things, score):
         collides_with = None
    
         for thing_image, thing_rect in all_things:
             if frog_rect.colliderect(thing_rect):
                  score = score+100
                  collides_with = True
    
         return collides_with
    

    现在它应该在行中更改score

    detect = checkCollision(frog_rect, all_things, score)
    if detect:
        score = score+100
    

    但是如果你想在checkCollision 中改变它,那么你必须返回值scorecheckCollision 内的变量 score 是局部变量,它不会改变全局变量 score 中的值

     def checkCollision(frog_rect,all_things, score):
         collides_with = None
    
         for thing_image, thing_rect in all_things:
             if frog_rect.colliderect(thing_rect):
                  score = score+100
                  collides_with = True
    
         return collides_with, score
    

    然后你必须向全局 score 进行 assing

    detect, score = checkCollision(frog_rect, all_things, score)
    

    【讨论】:

    • 非常感谢您的建议!下落的物体现在已修复,但碰撞检测正在工作,但似乎只针对一些下落的物体,而不是全部,因为有时分数会上升,而对于某些水果则不会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多