三角形重心坐标公式
三角形重心的坐标可以通过其三个顶点的坐标计算得出,公式为((X1+X2+X3)/3,(Y1+Y2+Y3)/3)。12
这是因为在平面直角坐标系中,重心的坐标是顶点坐标的算术平均数
中间黑点是重心坐标
import pygame
from pygame.locals import *
import sys
import mathpygame.init()width, height = 800, 600
screen = pygame.display.set_mode((width, height))vertices = [(100, 400, 1), (200, 200, 1), (400, 300, 1)]angle = 0
rotation_speed = 2 # 可根据需要调整旋转速度
c=pygame.time.Clock()
f=False
suofang=100
ax=0
ay=0
bx=0
by=0
cx=0
cy=0ci=0
def rotate_point(point, angle):x, y, z = pointnew_x = x * math.cos(math.radians(angle)) - z * math.sin(math.radians(angle))new_z = x * math.sin(math.radians(angle)) + z * math.sin(math.radians(angle))return (new_x, y, new_z)def draw_triangle(vertices):#points = [rotate_point(vertex, angle) for vertex in vertices]global ciglobal axglobal ayglobal bxglobal byglobal cxglobal cypoints = []for vertex in vertices:rotated_vertex = rotate_point(vertex, angle)points.append(rotated_vertex)#pygame.draw.polygon(screen, (255, 0, 0), [(width/2 + p[0], height/2 - p[1]) for p in points])transformed_points = []for p in points:if ci==0:ax=p[0]*30/suofang +300 # 将x坐标用透视投影在屏幕上ay=p[1]*30/suofang +200# 将y坐标用透视投影在屏幕上transformed_points.append((ax, ay)) # 将转换后的坐标添加到列表中#print(']]',0)if ci==1:bx=p[0]*30/suofang +200# 将y坐标用透视投影在屏幕上by=p[1]*30/suofang +200# 将y坐标用透视投影在屏幕上transformed_points.append((bx, by)) # 将转换后的坐标添加到列表中#print("]",1)if ci==2:cx=p[0]*30/suofang +200# 将y坐标用透视投影在屏幕上cy=p[1]*30/suofang +200# 将y坐标用透视投影在屏幕上transformed_points.append((cx, cy)) # 将转换后的坐标添加到列表中#print("]",2)# x = p[0]*30/suofang +300 # 将x坐标用透视投影在屏幕上# y = p[1]*30/suofang +200# 将y坐标用透视投影在屏幕上#transformed_points.append((x, y)) # 将转换后的坐标添加到列表中if (ci>=2):ci=0else:ci=ci+1print(p,';;')# 绘制多边形pygame.draw.polygon(screen, (200, 200, 200), transformed_points)while True:screen.fill((255, 255, 255))c.tick(70)for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()keys = pygame.key.get_pressed()if keys[pygame.K_UP]:f = Trueif event.type == pygame.KEYUP:f = Falseif f==True:suofang=suofang-1draw_triangle(vertices)angle += rotation_speedprint("....",ax,ay,bx,by,cx,cy)zx = (ax + bx + cx) / 3zy = (ay + by + cy) / 3pygame.Surface.set_at(screen, (int(zx), int(zy)),(190, 90, 90))pygame.display.flip()