【发布时间】:2016-11-05 07:22:05
【问题描述】:
我目前正在尝试实现自己的 SAT(分离轴定理)碰撞检测系统,但遇到了问题。在第 34 行,我收到以下错误消息:
第 34 行,发生冲突 轴 = (v[1], -v[0]) TypeError: 'int' 对象不可下标
奇怪的是 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 行
【问题讨论】:
-
for v in range(len(p.vectors)): 这是一个 int 列表,你正在查看的 v 是一个 int
-
第 34 行是哪一行?
-
在
v你有号码 - 即。123- 所以你尝试做axis = (123[1], -123[0])。也许你需要axis = (p.vectors[v][1], -p.vectors[v][0]) -
好的,我修复了那部分,在其他地方遇到了一些错误,但我会尝试自己修复这些错误。谢谢。我应该关闭它还是什么?这是我的第一篇文章。
-
嘿,如果你能验证我的答案,如果它有用,我将不胜感激。谢谢。
标签: python collision-detection separating-axis-theorem