Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用边界的x和y坐标进行Python碰撞检测_Python_Collision Detection_Detection_Turtle Graphics - Fatal编程技术网

使用边界的x和y坐标进行Python碰撞检测

使用边界的x和y坐标进行Python碰撞检测,python,collision-detection,detection,turtle-graphics,Python,Collision Detection,Detection,Turtle Graphics,我正在做一个python海龟游戏,海龟可以用命令移动,但它必须能够检测屏幕上的矩形和圆形以及边框的碰撞。我不知道怎么做,有人能帮忙吗?碰撞很容易!在讨论细节之前,您需要了解如何获得两点之间的距离。如果你以前没有做过这件事,那就是毕达格 如果在一个平面上画两个点(图上的红色点),它们之间的最短距离是直接从一个点到另一个点,无需进行任何转弯,这就是点之间的距离。在上图中,y为纵轴,x为横轴。点d和e之间的水平距离由值b表示。点d和e之间的垂直距离由值a表示。因此 a=d.y-e.y b=d.x-e.

我正在做一个python海龟游戏,海龟可以用命令移动,但它必须能够检测屏幕上的矩形和圆形以及边框的碰撞。我不知道怎么做,有人能帮忙吗?

碰撞很容易!在讨论细节之前,您需要了解如何获得两点之间的距离。如果你以前没有做过这件事,那就是毕达格

如果在一个平面上画两个点(图上的红色点),它们之间的最短距离是直接从一个点到另一个点,无需进行任何转弯,这就是点之间的距离。在上图中,y为纵轴,x为横轴。点d和e之间的水平距离由值b表示。点d和e之间的垂直距离由值a表示。因此

a=d.y-e.y
b=d.x-e.x

虽然a和be可能是负数,但这并不重要,因为我们在下一步中会使用a

为了得到c的值,我们必须得到a和b的平方和的平方根。一开始可能听起来很棘手,但很容易

Python代码 用python实现这一点很简单。

现在我们得到了两点d和e之间的距离。假设d和e有半径rd和re。然后,我们可以通过从圆心之间的距离减去每个半径来检查圆d是否与圆e碰撞。所以c变成了

c -= rd - re
如果c小于或等于零,则圆之间存在碰撞

def collision(d, e, rd, re):
    a = d.y-e.y
    b = d.x-e.x
    c = ((a**2)+(b**2))**0.5
    if c > 0:
        # no collision
        return False
    return True
矩形 矩形更容易一些,检查一个点是否在矩形内只需要一些if语句。让这些变量表示矩形x=x位置,y=y位置,w=宽度,h=高度。假设要检查点p是否与矩形碰撞

def check_rect_collision(p, x, y, w, h): 
    if p.x >= x and p.x <= x+w and p.y >= y and p.y <= y+h:
        # collision between p and rectangle
        return True
    return False
def检查直接碰撞(p,x,y,w,h):

如果p.x>=x且p.x=y且p.y测试与圆的碰撞是微不足道的--请使用
distance()
方法测量从光标中心到另一个位置或中心的距离。给定圆的
中心
位置及其
半径

def circle_collision(the_turtle, center, radius):
    return the_turtle.distance(center) <= radius
也就是说,默认海龟大小为20像素的一半,乘以
dx
dy
的平均值加上海龟周围边框的宽度。或者类似的近似值

检测矩形碰撞也相当简单:

def rectangle_collision(the_turtle, x, y, width, height):
    tx, ty = the_turtle.position()

    return x <= tx <= x + width and y <= ty <= y + height
def矩形\u碰撞(矩形、x、y、宽度、高度):
tx,ty=海龟位置()

返回x花了我一点时间。。很少的在
collision()?同样,在
中检查\u rect\u collision()
您说的是
x+width
,但参数是
w
。y+高度和h的情况同上。
def circle_collision(the_turtle, center, radius):
    dx, dy, border = the_turtle.shapesize()

    return the_turtle.distance(center) <= radius + 5 * (dx + dy) + border
def rectangle_collision(the_turtle, x, y, width, height):
    tx, ty = the_turtle.position()

    return x <= tx <= x + width and y <= ty <= y + height
def rectangle_collision(the_turtle, llx, lly, urx, ury):
    x, y = the_turtle.position()

    return llx <= x <= urx and lly <= y <= ury