Pygame-具有两个CIRCLES的碰撞检测 [英] Pygame - Collision detection with two CIRCLES

查看:140
本文介绍了Pygame-具有两个CIRCLES的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个碰撞检测程序,其中的光标是半径为20的圆,当碰到另一个圆时应将其值更改为TRUE。出于测试目的,我在屏幕中心有一个固定的圆,半径为50。我能够测试光标圆是否碰到了该固定圆,但是由于它实际上正在测试它是否有效而无法正常工作打一个正方形而不是一个圆形。我对数学不是很好,也无法找到答案。我发现了如何测试光标是否在触摸它,但从未测试过两个半径不同的对象。

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 different radii.

如何检查两个圆之间的碰撞?谢谢!

How do I check for collision between two circles? Thanks!

这是我的代码:

#@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,my=p.mouse.get_pos()
    for event in p.event.get():
        if(event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE)):
            p.quit()

    ### MAIN TEST FOR COLLISION ###
    if(mx in range(x-radius,x+radius) and my in range(y-radius,y+radius)):
        hit=True
    else:
        hit=False

    p.draw.circle(display,colour("blue"),[x,y],radius,0)
    p.draw.circle(display,colour("white"),p.mouse.get_pos(),cursorRadius,0)

    xy=font.render(str(p.mouse.get_pos()),True,colour("white"))
    hitTxt=font.render(str(hit),True,colour("white"))
    display.blit(xy,[5,285])
    display.blit(hitTxt,[270,285])

    p.display.update()


推荐答案

只需检查两个中心之间的距离是否小于半径之和。想象两个圆圈几乎彼此不接触(请参见下图),然后在两个中心之间绘制一条线。该线的长度将为两个半径(如果您是拉丁人,则为半径)之和。因此,如果两个圆相交,则它们的中心之间的距离将小于半径的总和,如果两个圆不相交,则将大于半径之和。

Just check whether the distance between the two centers is less than the sum of the radiuses. Imagine the two circles just barely touching each other (see graphic below), then draw a line between the two centers. The length of that line will be sum of the two radiuses (or radii if you're Latin). So if the two circles intersect, the distance between their centers will be less than the sum of the radiuses, and if they don't intersect, it will be more than the sum.

这篇关于Pygame-具有两个CIRCLES的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆