另一种方法是在每个点之间画一条线,然后你可以用线制作对象,然后进行线交叉以检查碰撞。我最近制作了一个程序,使用来自维基百科的数学来做到这一点
#check if 2 lines are intersecting
#lines are 2 pygame Vector2
def LineIntersect(line1, line2):
#the math is from wikipedia
x1 = line1[0].x
y1 = line1[0].y
x2 = line1[1].x
y2 = line1[1].y
x3 = line2[0].x
y3 = line2[0].y
x4 = line2[1].x
y4 = line2[1].y
#denominator
den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if den == 0:
return
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den
if t > 0 and t < 1 and u > 0 and u < 1:
pt = Vector2()
pt.x = x1 + t * (x2 - x1)
pt.y = y1 + t * (y2 - y1)
return pt
return
您可以对第一种方法执行的另一种方法是通过消除直线上的点来简化形状。我做了一个测试,得到了以下结果
,其中黑点被移除,红色是简化的形状。不太确定从那里做什么,所以我想我的第一种方法效果最好?这是它的代码
def Prepare(Points):
New_points = [Points[0]]
last_point = Vector2(Points[0])
for i in range(1,len(Points)-1,1):
p = Vector2(Points[i])
Dir = p - last_point
if i < len(Points) - 1:
New_dir = Points[i+1] - p
New_dir = New_dir.normalize()
angle = Dir.angle_to(New_dir)
if abs(angle) > 15:
New_points.append(Points[i])
#print(last_point.angle_to(p))
pygame.draw.circle(screen,(255,0,0),(int(p.x),int(p.y)),5)
last_point = p
New_points.append(Points[-1])
return New_points
我所做的是从上一个点到当前点和下一个点的方向,如果差异超过 15 度,它是一个角落,我添加到新点