【问题标题】:Pygame .Rect won't "collide" with mousePygame .Rect 不会与鼠标“碰撞”
【发布时间】:2013-09-01 02:22:22
【问题描述】:

我正在开发一个简单的游戏,并使用小圆圈“系统”。我希望能够单击每个系统,以便稍后在游戏中使用它做更多事情,但我很难识别仅单击一次。我将随机生成的坐标传递给字典,然后应使用鼠标位置检查每个矩形的碰撞,但由于某种原因不再起作用。任何帮助表示赞赏。

这里是一些更相关的代码。

    for i in range(NumSystems):

    SysSize = random.randint(3,SystemSize)
    SysY = random.randint(SystemSize*2,GVPHEIGHT-SystemSize*2)
    SysX = random.randint(OverLayWidth+SystemSize*2,WINWIDTH-SystemSize*2)



    SysList[str('SysNum')+str(i)] = ((SysSize,(SysX,SysY)))
    SysCoords[str('SysNum')+str(i)] = pygame.draw.circle(DISPLAYSURF, WHITE, (SysX,SysY), SysSize, 0)

    pygame.display.update()

    #time.sleep(.25)


#Code above is putting the random Coords into a dictionary.
while True:
    MousePos=mouse.get_pos()
    for event in pygame.event.get():
        if event.type == QUIT:
           pygame.QUIT()
           sys.exit()
        elif event.type == KEYDOWN:
            # Handle key presses

            if event.key == K_RETURN:
                #Restarts the map
                main()
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                SysClicky(MousePos)
                if SysClicked == True:
                    print('Clicked System')
                elif SysClicked == False:
                    print('Something Else Clicked')






def SysClicky(MousePos):

for i in range(NumSystems):
    print('Made to the SysClicky bit')
    if SysCoords['SysNum'+str(i)].collidepoint(MousePos):
        SysClicked = True
        print(SysClicked)
        return SysClicked
    else:

        SysClicked = False
        return SysClicked

【问题讨论】:

    标签: mouseevent clickonce pygame python-3.2


    【解决方案1】:

    我不清楚 SysList / SysX/Y, SysCoords 是什么。它是否包含 SysCoords 中项目的宽度、高度?如果是这样,那已经在Rect()

    systems 下方是您的 dictRects。

    代码如下:

    def check_collisions(pos):
        # iterate dict, check for collisions in systems
        for k,v in systems.items():
            if v.collidepoint(pos):
                print("clicked system:", k)
                return
    
        print("clicked something else")
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                check_collisions(event.pos)
    
        # render 
    

    【讨论】:

    • 关于列表的代码只是多余的,我忘了删除它。非常感谢!这正是我需要的,然后是一些
    【解决方案2】:

    Pygame rect 对象有一个 collidepoint 内置方法,它接受一个坐标并根据碰撞返回一个布尔值。您可以像这样将鼠标坐标输入到函数中:

    MousePos=mouse.get_pos()
    if mySurface.get_rect().collidepoint(MousePos):
        doSomething()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多