【发布时间】:2018-11-28 02:52:00
【问题描述】:
我正在开发一个 python 海龟游戏,其中海龟可以通过命令移动,但它必须能够检测与屏幕上的矩形和圆形以及边框的碰撞。我不知道该怎么做,有人可以帮忙吗?
【问题讨论】:
标签: python collision-detection detection turtle-graphics
我正在开发一个 python 海龟游戏,其中海龟可以通过命令移动,但它必须能够检测与屏幕上的矩形和圆形以及边框的碰撞。我不知道该怎么做,有人可以帮忙吗?
【问题讨论】:
标签: python collision-detection detection turtle-graphics
碰撞很容易!在深入了解之前,您需要了解如何获得两点之间的距离。如果您之前没有这样做,那就是 pythag!
如果你在一个平面上画出两点(图中红点),它们之间的最短距离是直接从一个点到另一个点,不需要任何转弯,这就是两点之间的距离。在上图中,设 y 为纵轴,x 为横轴。点 d 和 e 之间的水平距离由值 b 表示。点 d 和 e 之间的垂直距离由值 a 表示。这样……
a = d.y - e.y
b = d.x - e.x
虽然 a 和 be 可能是负数,但这没关系,因为我们在下一步中将它们平方。
为了得到 c 的值,我们必须得到 a 和 b 的平方和的平方根。一开始可能听起来很棘手,但很容易!
Python 代码
在 python 中做到这一点很简单。
c = ((a**2)+(b**2))**0.5
# a**2 is a squared
# anything to the power of 0.5 is square rooted, test it in console
# 25**0.5 = 5.0
# 5**2 = 25
我们现在有了 d 和 e 两点之间的距离。假设 d 和 e 的半径为 rd 和 re。然后,我们可以通过从圆心之间的距离中减去每个半径来检查圆 d 是否与圆 e 碰撞。所以 c 变成了...
c -= rd - re
如果 c 小于或等于 0,则说明圆之间发生碰撞!
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
【讨论】:
collision() 中你的意思是if c > 0 而不是if a > 0:?同样在check_rect_collision() 你说x+width 但参数是w。 y+height 和 h 同上。
测试与圆的碰撞很简单——使用distance() 方法测量从光标中心到另一个海龟的位置或中心。给定一个圈子的center 位置及其radius:
def circle_collision(the_turtle, center, radius):
return the_turtle.distance(center) <= radius
如果您需要知道乌龟的鼻子是否接触了圆圈,您可以将乌龟的一半大小添加到radius,以获得(可能调整大小)非常粗略的光标:
def circle_collision(the_turtle, center, radius):
dx, dy, border = the_turtle.shapesize()
return the_turtle.distance(center) <= radius + 5 * (dx + dy) + border
即默认海龟大小的一半 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 rectangle_collision(the_turtle, llx, lly, urx, ury):
x, y = the_turtle.position()
return llx <= x <= urx and lly <= y <= ury
setworldcoordinates() 的坐标参数。
【讨论】: