Pygame circle collision?

泪湿孤枕 提交于 2019-12-13 00:34:45

问题


I am using pygame to make a simple game. I am having issues with circle collisions. I am getting the following error:
"AtributeError: 'pygame.Rect' object has no attrinute 'rect'"

Here is the particular code I am having issues with below:

    if pygame.sprite.collide_circle(hero_circle, enemy_circle):
          gameover()

Thanks in advance!


回答1:


Use pygame.mask to create a collision mesh for your objects and use the mesh to do collision detections.

In more detail:

  1. Create an image file for both of your circles and set the bg color to something you will not use anywhere else.
  2. Set that color to "transparent" in your image editor.
  3. Import the images.
  4. Create a mesh for them with pygame.mask and set it to make transparent pixels non-collidable.
  5. Use the generated mask as your collision detection mesh.
  6. PROFIT

(Technically this is just doing collision detection of a circle shaped area on a rectangle, but who cares!)




回答2:


pygame.draw.rect()
draw a rectangle shape
rect(Surface, color, Rect, width=0) -> Rect

Draws a rectangular shape on the Surface. The given Rect is the area of the rectangle. The width argument is the thickness to draw the outer edge. If width is zero then the rectangle will be filled.

Keep in mind the Surface.fill() method works just as well for drawing filled rectangles. In fact the Surface.fill() can be hardware accelerated on some platforms with both software and hardware display modes.




回答3:


Just like how gmk said it but if your are using circles instead of rectangles, you should use this pygame function :

pygame.draw.circle(surface, color, center_point, radius, width)

This draws a circle on your surface (which would go in the surface area). Clearly the color requires a list of numbers (RGB anyone?). Your center_point decides the location of your circle since it will be the location of the center of your circle. The radius will need a number to set the radius of the circle (using the number like 25 will set your radius at 25 pixels/diameter at 50 pixels). the width section is optional as it sets the thickness of the perimeter of your circle (having 0 will have none at all). If you are not using circles, you should change your title... But anyways, I hope this helps you!



来源:https://stackoverflow.com/questions/27642234/pygame-circle-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!