天道酬勤,学无止境

How to detect collision between objects in Pygame?

I'm making a sidescrolling game in Pygame, and if the fox sprite collides with the tree, it is supposed to print "COLLIDE". But it doesn't work. How can I fix this to detect collision between the fox and the tree? Here's the code:

if foxsprite1 > xtree  and foxsprite1 < xtree + treewidth or foxsprite1 + treewidth > xtree and foxsprite1 + treewidth < xtree + treewidth:
        print ("COLLIDE")

xtree is the x coordinate of the tree, treewidth is the width of the tree, and foxsprite1 is the fox.

评论

Keep object position and size as pygame.Rect()

fox_rect = pygame.Rect(fox_x, fox_y, fox_width, fox_height)
tree_rect = pygame.Rect(tree_x, tree_y, tree_width, tree_height)

and then you can use

if fox_rect.colliderect(tree_rect): 
     print("COLLIDE")

Rect() is very usefull. You can use it to blit

screen.blit(fox_image, fox_rect)

You can use it to center object on screen

screen_rect = screen.get_rect()

fox_rect.center = screen_rect.center

or to keep object on the screen (and it can't leave screen)

if fox_rect.right > screen_rect.right:
    fox_rect.right = screen_rect.right

if fox_rect.left < screen_rect.left:
    fox_rect.left = screen_rect.left

or simpler

fox_rect.clamp_ip(screen_rect)

see: Program Arcade Games With Python And Pygame and Example code and programs

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • How do you detect a collision between 2 surface objects that are part of a Sprite class in pygame? [duplicate]
    This question already has an answer here: pygame.sprite.groupcollide() does not work when trying to implement collision in pygame [duplicate] (1 answer) Closed 10 months ago. I made an enemy class and a player class for a pygame game and I'm trying to figure out how to detect collisions between them. I've tried a lot of different methods, and they don't work, because they need you to use a Rect object and I use a Surface object. Can you tell me what code to add to detect collisions between to Surface Objects? Here is my code: import pygame from pygame.locals import * from sys import exit
  • How to detect collisions between two rectangular objects or images in pygame
    I am making a game in which the player has to use a bowl to catch falling items. I have some images of items in a list and an image of a bowl that is used to catch the items. The items keep on falling and reset to the top of the screen if they reach the boundary (bottom edge). I got this logic done which allows the items to fall but I do not know how to detect when there is a collision between the bowl and item. My code: import math import pygame import random pygame.init() display_width = 800 display_height = 600 game_display = pygame.display.set_mode((display_width, display_height)) clock =
  • Pygame碰撞检测对象和矩形(Pygame collision detect with object and rect)
    问题 是的,我在问关于这个程序的另一个问题:D 无论如何,我目前有一个程序,它在屏幕上创建两行,它们之间有一个可以滚动的间隙。 从这里开始,我显然需要查看两个对象是否发生碰撞。 因为我只有一个精灵和一个矩形,所以我认为为它们创建两个类有点毫无意义和矫枉过正。 但是,我只能找到与我显然不需要的课程相关的教程。 所以,我的问题真的是:是否可以测试标准图像和 Pygame rect之间的碰撞? 如果不是,我如何转换图像、矩形或两个精灵来做到这一点。 (最好不要使用类。) 注意:图像和矩形的创建方式如下(如果有区别的话) bird = pygame.image.load("bird.png").convert_alpha() pipeTop = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,0),(30,height))) pipeBottom = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,900),(30,-bheight))) 回答1 图像本身没有位置。 您无法测试 rect 与未放置在世界中的事物之间的碰撞。 我建议创建一个 Bird 类和一个 Pipe 类,它们都将继承 pygame.Sprite。 Pygame 已经内置了碰撞检测。 一个简短的例子 bird =
  • Detect collision between textbox and circle in pygame
    I'm trying to create a game in python where one can drag a textbox around the screen, but whenever it touches the borders of a circle around it, I want the loop to start over, but with a different text (by storing all text-strings in a list, but I'm not that far, yet). This is how far I have come: import pygame import ptext pygame.init() gameDisplay = pygame.display.set_mode((500, 500)) gameDisplay.fill((255,255,255)) x = 190 y = 230 a = 250 b = 250 text = "ExampleText 1." def textbox(x,y): ptext.draw(text, (x,y), color = (0,0,0)) def circle(a,b): pygame.draw.circle(gameDisplay, (0,0,0), (250
  • 如何检测pygame中两个图像的碰撞[重复](How to detect collision of two images in pygame [duplicate])
    问题 这个问题在这里已经有了答案: 如何检测 pygame 中两个矩形对象或图像之间的碰撞(1 个回答) Pygame - 如何使hitbox 与敌人的移动一起工作? [重复] (1 个回答) 去年关闭。 我想知道如何在 pygame 中进行碰撞检测。 我的游戏不使用精灵,它只是 blit 2 个图像。 我如何检查它们是否发生碰撞? 我知道有 sprite.collide,但它不使用精灵。 有没有办法通过比较每个图像的 x 和 y 值来检查碰撞? def fish(x,y): gameDisplay.blit(fishImg,(x,y)) def enemy(enemyX,enemyY): gameDisplay.blit(enemyImg,(enemyX,enemyY)) def main(): x = displayWidth/2 y = displayHeight/2 enemyX = random.randint(0,displayWidth) enemyY = random.randint(0,displayHeight) xChange = 0 yChange = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if
  • 如何在Pygame中检测两个矩形对象或图像之间的碰撞(How to detect collisions between two rectangular objects or images in pygame)
    问题 我正在做一个游戏,其中玩家必须使用碗抓落的物品。 我在列表中有一些项目的图像,还有一个用来捕获项目的碗的图像。 这些项目持续下降并在到达边界(底部边缘)时重置到屏幕顶部。 我完成了使物品掉落的逻辑,但是我不知道如何检测碗和物品之间是否发生碰撞。 我的代码: import math import pygame import random pygame.init() display_width = 800 display_height = 600 game_display = pygame.display.set_mode((display_width, display_height)) clock = pygame.time.Clock() pygame.display.set_caption("Catch the Ball") white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) blue = (0, 255, 0) player_img = pygame.image.load("Images/soup.png") thing_imgs = [pygame.image.load('Images/muffin.png'), pygame.image.load('Images/dessert.png')
  • Python Pygame.Rect() 检测碰撞
    最近在学Pygame,花一段时间做了一个异常简陋版的"飞机大战"。 然后吧,就遇到了一个问题: 怎么检测碰撞呢?(个人太菜…) 按照网上教程比较普遍的方法(也可能是我没看见别的),碰撞检测依次计算移动物体与被碰撞物体各个边之间坐标是否相交.例如下列代码,检测小球与窗口的碰撞: if self.vector.x > WINDOW_X - self.image.get_width(): self.vector.x = WINDOW_X -self.image.get_width() elif self.vector.x < 0: self.vector.x = 0 可是,因为这种方法由于需要加减各种数值,很容易多加一个少减一个,出现乱七八糟的错误。所以我想了一种相对简便些的方法。 Pygame.Rect正式登场! pygame.Rect(enemy1[i-counte1][0]+3.5,enemy1[i-counte1][1]+3.5,43-3.5,57-3.5).colliderect(pygame.Rect(mems[0]+5,mems[1]+5,102-5,126-5)) #:D有些长 使用Pygame自带的方法Rect()将Surface对象转换成矩形对象,然后检测碰撞。 语法大概是这样的: pygame.Rect(for_x,for_y,for_width,for
  • Detecting collisions between polygons and rectangles in Pygame
    So I am trying to make an among us type game with pygame. I just started, so I don't have much of anything and am working on the map right now. However, one thing I'm struggling with is the collision logic. The map has an elongated octagon shape for now, but I think no matter the shape I will use something like a pygame polygon. When I ran the code I have now, which checks for a collision between my player (pygame rectangle) and the walls (pygame polygon) it says: TypeError: Argument must be rect style object I've figured out this is because of the pygame polygon returning a rectangle, but not
  • Pygame:碰撞检测
    文章目录 (一)碰撞检测的原理(二)手动写代码实现碰撞检测1️⃣版本一2️⃣版本二 (三)使用sprite 提供的现成的碰撞检测函数 🚴大家好!我是近视的脚踏实地,虽然近视,但是脚踏实地,这一篇来学习游戏中的碰撞检测,然后继续完善未完成的小游戏 (一)碰撞检测的原理 大部分游戏都是要做碰撞检测的,因为你要知道小球是否发生了碰撞,子弹是否击中了目标等等。那么其实碰撞原理也很简单,事实就是检测两个精灵是否存在重叠的部分。 比如上面这张图👆,width表示的就是圆心的距离,r1、r2分别表示他们的半径,此时width是大于他们的半径之和的,那么他们就是没有产生重叠,也就是没有发生碰撞,那么当碰撞发生的那一刹那,如下图👇 可以看到此时width是等于r1+r2的,圆心距刚好等于两个半径之和.再来看看下面第三张图片 可以看到当他们重叠,产生交集的时候,width是小于r1+r2的,所以得到的结果就是判断两个小球是否发生碰撞,我们只要检测两个小球的圆心距是否小于等于他们两个半径之和就🉑了 (二)手动写代码实现碰撞检测 1️⃣版本一 collide_check.py:👇 import pygame import sys import math from pygame.locals import * from random import * # 球类继承自Spirte类 class Ball
  • Pygame collision detect with object and rect
    Yep, I'm asking another question about this program :D Anyway, I currently a program that creates two lines on the screen with a gap in between them that can scroll. From here, I obviously need to see if the two objects are colliding. Since I only have one sprite and one rectangle I thought it was slightly pointless and overkill to make two classes for them. However, I can only find tutorials relating to classes which I obviously don't need. So, my question really is: Is it possible to test for collision between a standard image and a Pygame rect? If it is not, how can I convert either the
  • Python中pygame模块pygame.sprite.groupcollision碰撞检测的详解与测试
    在游戏开发中,非常重要的编程工作就是进行碰撞检测。在python的pygame模块中的sprite精灵类提供了多种方便快捷的碰撞检测方法。比如矩形碰撞检测、圆形碰撞检测、遮罩碰撞检测,这些方法基本都是单个对单个的物体进行检测,如果涉及到敌我双方都有很多对象时,比如飞机大战中的我方子弹与地方飞机的碰撞检测,用上述方法可能就得进行循环嵌套,这样略显麻烦。 针对分组对象的碰撞检测,pygame中还有一种简单的碰撞检测方法:pygame.sprite.groupcollision(),网上关于介绍它的详细使用方法的文章不多,我经过反复研究和测试,终于弄清楚了它的使用方法、使用场景以及使用效果,希望对你有参考价值。 一、 功能说明 官方文档如下: Find all sprites that collide between two groups. groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect attribute of each Sprite or by
  • How to detect collision of two images in pygame [duplicate]
    This question already has answers here: How to detect collisions between two rectangular objects or images in pygame (1 answer) Pygame - How to make hitbox work with enemy movement? [duplicate] (1 answer) Closed last year. I was wondering how to do collision detection in pygame. My game doesn't use sprites, it just blits 2 images. How could I check if they are colliding? I know there is sprite.collide, but it doesn't use sprites. Is there some way to check collision by comparing the x and y values of each image? def fish(x,y): gameDisplay.blit(fishImg,(x,y)) def enemy(enemyX,enemyY)
  • 检测pygame中文本框和圆圈之间的碰撞(Detect collision between textbox and circle in pygame)
    问题 我正在尝试在 python 中创建一个游戏,可以在屏幕上拖动一个文本框,但是每当它触及围绕它的圆圈的边界时,我希望循环重新开始,但使用不同的文本(通过存储所有文本-strings 在列表中,但我还没有那么远)。 这是我走了多远: import pygame import ptext pygame.init() gameDisplay = pygame.display.set_mode((500, 500)) gameDisplay.fill((255,255,255)) x = 190 y = 230 a = 250 b = 250 text = "ExampleText 1." def textbox(x,y): ptext.draw(text, (x,y), color = (0,0,0)) def circle(a,b): pygame.draw.circle(gameDisplay, (0,0,0), (250, 250), 210, 5) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEMOTION: if event.buttons[0]: x
  • 多边形和圆形之间的碰撞检测(Collision detection between a polygon and a circle)
    问题 我想知道 pygame 中的碰撞检测是如何工作的,在一个多边形和一个圆之间,用于足球比赛。 我想要做的是让一个球朝着汽车撞击它的方向移动。请有人修复我的代码,我被卡住了!! 如果您运行以下代码,两辆车将移动,但如果它们击中球,则不会发生任何事情,并且没有错误消息(第 26 行,我尝试使其工作)。 对于初学者,我只希望它打印(“你好”)。 如果有人可以提供帮助,我将不胜感激。 谢谢你 import pygame from pygame.math import Vector2 pygame.init() screen = pygame.display.set_mode((1150, 800)) redx = 50 redy = 30 bluex = 100 bluey = 30 clock = pygame.time.Clock() BLUECAR_ORIGINAL = pygame.Surface((bluex, bluey), pygame.SRCALPHA) pygame.draw.polygon( BLUECAR_ORIGINAL, (0, 0, 255), [(0, 30), (50, 20), (50, 10), (0, 0)]) bluecar = BLUECAR_ORIGINAL REDCAR_ORIGINAL = pygame.Surface((redx
  • Pygame - 两个圆圈的碰撞检测(Pygame - Collision detection with two CIRCLES)
    问题 我正在制作一个碰撞检测程序,其中我的光标是一个半径为 20 的圆,当它碰到另一个圆时应该将一个值更改为 TRUE。 出于测试目的,我在屏幕中心有一个半径为 50 的固定圆。我可以测试光标圆是否碰到了固定圆,但它不能正常工作,因为它实际上是在测试它是否是击中一个正方形而不是一个圆形。 我数学不太好,一直找不到答案。 我已经找到了如何测试光标是否正在触摸它,但从来没有测试过两个具有两个不同半径的对象。 如何检查两个圆之间的碰撞? 谢谢! 这是我的代码: #@PydevCodeAnalysisIgnore #@UndefinedVariable import pygame as p, sys, random as r, math as m from pygame.locals import * from colour import * p.init() w,h=300,300 display = p.display.set_mode([w,h]) p.display.set_caption("Collision Test") font = p.font.SysFont("calibri", 12) x,y=150,150 radius=50 cursorRadius=20 count=0 hit=False while(True): display.fill([0,0,0]) mx
  • PyGame Collision detection for pong and keeping the paddles on screen [duplicate]
    This question already has answers here: How do I detect collision in pygame? (4 answers) How to detect collisions between two rectangular objects or images in pygame (1 answer) Sometimes the ball doesn't bounce off the paddle in pong game (1 answer) Closed 9 months ago. So my problem here is that I don't want to use classes because I don't fully understand them yet nor do I want to use sprites. I have uploaded two images to the program I am able to move the paddles and get the ball to move and bounce off the top and bottom. However I cannot get the ball to bounce off the paddles. Also I cannot
  • PyGame 碰撞检测,用于乒乓球并将球拍保持在屏幕上 [重复](PyGame Collision detection for pong and keeping the paddles on screen [duplicate])
    问题 这个问题在这里已经有了答案: 如何检测pygame中的碰撞? (4 个回答) 如何检测 pygame 中两个矩形对象或图像之间的碰撞(1 个回答) 有时在乒乓球比赛中球不会从球拍上反弹(1 个回答) 9 个月前关闭。 所以我的问题是我不想使用类,因为我还没有完全理解它们,也不想使用精灵。 我已将两张图片上传到程序中,我可以移动球拍并使球移动并从顶部和底部反弹。 但是我无法让球从桨上弹起。 我也不能阻止桨从屏幕上掉下来或从屏幕上掉下来。 任何帮助将不胜感激,谢谢。 import sys import pygame pygame.init() size = width, height = 1000, 800 screenColor = 0, 0, 0 outline = 0, 0, 255 paddleOne = pygame.image.load("PONGPADDLE.png") paddleTwo = pygame.image.load("PONGPADDLE.png") ball = pygame.image.load("Bullet.png") paddleOnerect = paddleOne.get_rect() paddleTworect = paddleTwo.get_rect() ballrect = ball.get_rect() speed = [1, 1
  • Implementing a collision detect feature between a Rect object and a ball in pygame [duplicate]
    This question already has an answer here: Sometimes the ball doesn't bounce off the paddle in pong game (1 answer) Closed 6 months ago. import pygame, random, time # main function where we call all other functions, start the game loop, quit pygame and clean up the window. Inside we create a game object, display surface, and start the game loop by calling the play method on the game object. There is also a set caption with the title of the game. def main(): pygame.init() size =(500,400) surface=pygame.display.set_mode(size) pygame.display.set_caption('Pong v2') game = Game(surface) game.play()
  • Pygame - Collision detection with two CIRCLES
    I'm making a collision detection program where my cursor is a circle with a radius of 20 and should change a value to TRUE when it hits another circle. For testing purposes, I have a stationary circle in the centre of my screen with a radius of 50. I'm able to test whether the cursor circle has hit the stationary circle but it doesn't quite work properly because it's actually testing if it's hitting a square rather than a circle. I'm not very good with maths and I haven't been able to find the answer to this. I've found how to test if the cursor is touching it but never two objects with two
  • pygame sprite wall collision [duplicate]
    This question already has answers here: How do I detect collision in pygame? (4 answers) How to detect collisions between two rectangular objects or images in pygame (1 answer) Adding collision to maze walls (1 answer) How to implement barriers to stop the player moving through walls (1 answer) Closed 2 months ago. I am working on a platform game in python and pygame. The entire code can be found at "https://github.com/C-Kimber/FBLA_Game". The issue I am having is with the collision between the player sprite and wall sprites, specifically the corners. When the player is pressing a x movement