pygame中的collidepoint函数是如何工作的? [英] How does the collidepoint function in pygame work?
问题描述
所以我正在做一个关于 pong 的实验,我对 pygame 中的碰撞点函数的概念迷失了,它检查圆心是否在球拍内.在查看文档时,我仍然感到困惑,因为我对编程非常陌生,而且我真的很难适应并掌握向我抛出的新技能.如果有人能帮我解释一下,并给出一个基本的简单示例,我将不胜感激.
So I am doing a lab regarding pong and I was lost on the concept of collidepoint a function in pygame, which checks whether the center of the circle is inside the paddle. Upon looking at documentation I was still confused since I am very new to programming and I am really having a hard time settling in and getting a grasp of the new skills thrown at me. I would really appreciate if someone could help me out by explaining it a bit more and maybe giving a basic simple example.
推荐答案
点碰撞记录在 PyGame Rect 类.
本质上,您将坐标传递给 pygame.Rect.collidepoint()
,如果该点在矩形的边界内,它将返回 True
.
Essentially you pass a co-ordinate to pygame.Rect.collidepoint()
, and it will return True
if that point is within the bounds of the rectangle.
import pygame
# Window size
WINDOW_WIDTH=400
WINDOW_HEIGHT=400
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Point Collision")
BLACK = ( 50, 50, 50 )
GREEN = ( 34, 139, 34 )
BLUE = ( 161, 255, 254 )
# The rectangle to click-in
# It is window-centred, and 33% the window size
click_rect = pygame.Rect( WINDOW_WIDTH//3, WINDOW_HEIGHT//3, WINDOW_WIDTH//3, WINDOW_HEIGHT//3 )
rect_colour = BLACK
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle all the events
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
mouse_position = pygame.mouse.get_pos() # Location of the mouse-click
if ( click_rect.collidepoint( mouse_position ) ): # Was that click inside our rectangle
print( "hit" )
# Flip the colour of the rect
if ( rect_colour == BLACK ):
rect_colour = GREEN
else:
rect_colour = BLACK
else:
print( "click-outside!" )
# update the screen
window.fill( BLUE )
pygame.draw.rect( window, rect_colour, click_rect) # DRAW OUR RECTANGLE
pygame.display.flip()
# Clamp the FPS to an upper-limit
clock.tick_busy_loop( 60 )
pygame.quit()
注意代码下半部分collidepoint()
的使用:
Note the use of the collidepoint()
in the lower half of the code:
if ( click_rect.collidepoint( mouse_position ) ):
这里的代码检查最近通过鼠标输入事件发现的坐标是否在 click_rect
(在主循环之前声明的 pygame.Rect)内.如果坐标在矩形内,则以不同的颜色绘制.
Here the code is checking that the co-ordinate recently discovered via a mouse-input event is within the click_rect
(a pygame.Rect declared before the main loop). If the co-ordinates are within the rectangle, it is draw in a different colour.
这里的大部分代码只是简单地打开窗口,然后运行主输入/更新循环.
The bulk of the code here is to simply open the window, and run the main input/update loop.
这篇关于pygame中的collidepoint函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!