我目前正在尝试实现我自己的SAT(分离轴定理)碰撞检测系统,但遇到了一个问题。在第34行我得到了这个错误消息:
line 34, in collision axis = (v[1], -v[0]) TypeError: 'int' object is not subscriptable
奇怪的是v不是int,而是元组。在
这是密码
import math
import pygame
WIDTH = 900
HEIGHT = 700
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
def dot(v1, v2):
return v1[0]*v2[0] + v1[1]*v2[1]
polygons = []
class Polygon():
def __init__(self, points):
self.points = points
self.vectors = []
for p1 in range(len(self.points)):
p2 = p1 + 1
if p2 > len(self.points) - 1:
p2 = 0
v = (self.points[p2][0] - self.points[p1][0], self.points[p2][1] - self.points[p1][1])#int object not subscriptable
self.vectors.append(v)
polygons.append(self)
def collision(self):
for p in polygons:
collision = True
if p.points != self.points:
for v in range(len(p.vectors)):
axis = (v[1], -v[0])
selfFirst = True
pFirst = True
for point in self.points:
if selfFirst == True:
selfFirst = False
projection = dot(point, axis)
selfMin = projection
selfMax = projection
else:
projection = dot(point, axis)
if projection < selfMin:
selfMin = projection
elif projection > selfMax:
selfMax = projection
for point in p.points:
if pFirst == True:
pFirst = False
projection = dot(point, axis)
pMin = projection
pMax = projection
else:
projection = dot(point, axis)
if projection < pMin:
pMin = projection
elif projection > pMax:
pMax = projection
if (selfMin > pMin and selfMin < pMax) or (selfMax > pMin and selfMax < pMax):
collision = True
else:
collision = False
return collision
polygon1 = Polygon([(0, 0), (100, 100), (0, 100)])
polygon2 = Polygon([(300, 300), (150, 0), (0, 150)])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0,0,0))
for polygon in polygons:
polygon.collision()
pygame.draw.polygon(screen, (0, 255, 0), polygon.points, 1)
pygame.display.flip()
clock.tick(60)
pygame.display.quit()
问题在34号线
这是一个关于变量命名的对象课程。在
在第27行中,
__init__()
中的v
分配给:v = (self.points[p2][0] - self.points[p1][0], self.points[p2][1] - self.points[p1][1])
然后在循环中,您重新分配它并删除以前的分配:
for v in range(len(p.vectors)):
len()
返回整数,range()
返回整数列表。因此,在每个循环中,v
都会从该范围中分配一个整数。因此,v
现在是一个整数,不可下标。在可能是这样的:
for v in p.vectors:
对你来说更好。在所以循环中的
v
是一个整数,访问一个整数的第一个/第二个位置是没有意义的(当v[1], -v[0]
时就是这样做的),因此你得到了关于可订阅的东西的错误。在在:
},可能在它们上面有位置},所以也许这会起作用:
^{pr2}$range
返回一个整数列表,因为您将另一个整数作为参数传递给它(len(p.vectors)
)。我不知道p.vectors
是什么,我假设是一个对象列表{0
和{相关问题 更多 >
编程相关推荐