[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
[pygame] Code: Center of Triangle
Worked this up today for myself, thought I'd post it in case someone
else found it useful.
import pygame
def CenterOfTriangle(A, B, C):
return (A[0] + B[0] + C[0])/3.0, (A[1] + B[1] + C[1])/3.0, (A[2] +
B[2] + C[2])/3.0
def CalculateDistance(a, b):
x, y, z = b[0] - a[0], b[1] - a[1], b[2] - a[2]
dist = x*x + y*y + z*z
return dist * dist
def NearestVert(triangle, pos):
distance = 99999999999999999999
v = -1
for i in range(len(triangle)):
temp = CalculateDistance(triangle[i], [pos[0], pos[1], 0])
if temp < distance:
distance = temp
v = i
assert(v >= 0)
return v
def main():
pygame.init()
screen = pygame.display.set_mode([640, 480], 0, 32)
quit = 0
triangle = [[132, 319, 0], [282, 120, 0], [434, 319, 0]]
center = CenterOfTriangle(*triangle)
v = -1
font = pygame.font.Font(None, 18)
pic = font.render('Center: %d, %d, %d Triangle: %s' %
(int(center[0]), int(center[1]), int(center[2]), triangle), 1, (0, 0, 0))
while not quit:
screen.fill((255, 255, 255))
pygame.draw.polygon(screen, (0, 0, 0), [triangle[0][:2],
triangle[1][:2], triangle[2][:2]], 1)
x, y, z = int(center[0]), int(center[1]), int(center[2])
screen.fill((255, 0, 0), [x-2, y-2, 4, 4])
screen.blit(pic, [0, 450])
pygame.display.flip()
pygame.event.pump()
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = 1
break
elif e.type == pygame.MOUSEBUTTONDOWN:
v = NearestVert(triangle, e.pos)
elif e.type == pygame.MOUSEMOTION:
if v > -1:
triangle[v] = [e.pos[0], e.pos[1], 0]
center = CenterOfTriangle(*triangle)
pic = font.render('Center: %d, %d, %d Triangle: %s'
% (int(center[0]), int(center[1]), int(center[2]), triangle), 1, (0, 0, 0))
elif e.type == pygame.MOUSEBUTTONUP:
v = -1
pygame.quit()
main()