python - Python中的形状旋转不正确
问题描述
我正在尝试在 pygame 中创建一个旋转平面。我将 3d (x, y, z) 坐标转换为屏幕坐标 (x, y),然后旋转屏幕坐标。这似乎在它同时在 x 和 y 轴上旋转时起作用,但是当它仅在一个轴上旋转时(我注释掉了 y 轴旋转)它是倾斜的。我似乎无法弄清楚为什么?
import pygame
import math
red = (255, 0, 0)
class Vector3:
def __init__(self, _x, _y, _z):
self.x = _x
self.y = _y
self.z = _z
class Vector2:
def __init__(self, _x, _y):
self.x = _x
self.y = _y
class Plane:
def draw(self, screen, value):
scale = 25
points = []
vertices = [Vector3(0, 1, 0),
Vector3(1, 1, 0),
Vector3(1, 0, 0),
Vector3(0, 0, 0)]
for vert in vertices:
x, y = vec3to2(vert)
points.append(Vector2(x * scale + 40, y * scale + 100))
print((x, y))
centerx = (points[0].x + points[1].x + points[2].x + points[3].x) / 4
centery = (points[0].y + points[1].y + points[2].y + points[3].y) / 4
for point in points:
rotx, roty = vec3rot(point, math.radians(value), centerx, centery)
point.x = rotx
#point.y = roty
pygame.draw.line(screen, red, (points[0].x, points[0].y), (points[1].x, points[1].y))
pygame.draw.line(screen, red, (points[1].x, points[1].y), (points[2].x, points[2].y))
pygame.draw.line(screen, red, (points[0].x, points[0].y), (points[3].x, points[3].y))
pygame.draw.line(screen, red, (points[3].x, points[3].y), (points[2].x, points[2].y))
pygame.draw.circle(screen, red, (int(centerx), int(centery)), 1)
def vec3to2(vect3):
try:
_x = vect3.x / vect3.z
except ZeroDivisionError:
_x = vect3.x
try:
_y = vect3.y / vect3.z
except ZeroDivisionError:
_y = vect3.y
return(_x, _y)
def vec3rot(vect3, theta, centerx, centery):
_x = centerx + (vect3.x - centerx) * math.cos(theta) - (vect3.y - centery) * math.sin(theta)
_y = centery + (vect3.x - centerx) * math.sin(theta) + (vect3.y - centery) * math.cos(theta)
return(_x, _y)
def main():
pygame.init()
screen = pygame.display.set_mode((640, 480))
v = 0
plane = Plane()
running = True
while running:
screen.fill((0, 0, 0))
plane.draw(screen, v)
pygame.display.flip()
v += 0.1
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
main()
解决方案
推荐阅读
- excel - 条件格式,如果单元格包含 2 个单元格中的特定文本,则突出显示单元格
- python - 使用 Gridfs 将 base64 字符串图像存储到 MongoDB
- php - 从百分比计算发生的事件
- python - 将理解列表打印为字符串
- javascript - 记忆游戏中的setTimeout
- python - 带有请求的 Python 自动结帐
- python - 我可以在 keras 中对部分模型运行指标吗?
- c# - MSBuild 和 Visual Studio 因错误的显式接口声明而崩溃
- excel - VBA中的拉马努金函数
- python - 在两个 Spark DataFrame 中逐行添加值