Python,用旋转矩阵把所有已知三维顶点逆时针旋转60度,并将新的三维顶点画出来
时间: 2024-02-27 18:54:58 浏览: 19
以下是 Python 中使用旋转矩阵将三维顶点逆时针旋转60度,并将新的三维顶点画出来的示例代码:
```python
import math
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
# 定义三维坐标点类
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# 定义旋转矩阵计算函数
def rotation_matrix(angle_x, angle_y, angle_z):
# 计算旋转矩阵
cos_x = math.cos(angle_x)
sin_x = math.sin(angle_x)
cos_y = math.cos(angle_y)
sin_y = math.sin(angle_y)
cos_z = math.cos(angle_z)
sin_z = math.sin(angle_z)
Rx = np.array([[1, 0, 0], [0, cos_x, -sin_x], [0, sin_x, cos_x]])
Ry = np.array([[cos_y, 0, sin_y], [0, 1, 0], [-sin_y, 0, cos_y]])
Rz = np.array([[cos_z, -sin_z, 0], [sin_z, cos_z, 0], [0, 0, 1]])
return np.dot(np.dot(Rz, Ry), Rx)
# 定义三维顶点逆时针旋转函数
def rotate_vertices(vertices, angle):
# 构造旋转矩阵
R = rotation_matrix(0, 0, angle)
# 依次旋转每个三维顶点
for i in range(len(vertices)):
point = vertices[i]
coords = np.array([point.x, point.y, point.z])
new_coords = np.dot(R, coords)
vertices[i] = Point(new_coords[0], new_coords[1], new_coords[2])
# 测试
vertices = [Point(1, 0, 0), Point(0, 1, 0), Point(0, 0, 1),
Point(1, 1, 0), Point(1, 0, 1), Point(0, 1, 1),
Point(1, 1, 1), Point(0, 0, 0)]
print("原顶点:", [(p.x, p.y, p.z) for p in vertices])
rotate_vertices(vertices, math.pi/3)
print("旋转后顶点:", [(p.x, p.y, p.z) for p in vertices])
# 绘制三维图形
fig = plt.figure()
ax = plt.axes(projection="3d")
x_vals = [p.x for p in vertices]
y_vals = [p.y for p in vertices]
z_vals = [p.z for p in vertices]
ax.scatter3D(x_vals, y_vals, z_vals, c=z_vals, cmap='Greens')
plt.show()
```
该代码定义了一个三维坐标点类 `Point`,以及一个旋转矩阵计算函数 `rotation_matrix` 和一个三维顶点逆时针旋转函数 `rotate_vertices`。`rotation_matrix` 函数接受三个角度参数,用于计算绕 X/Y/Z 轴旋转的旋转矩阵。`rotate_vertices` 函数接受一个三维顶点列表和一个旋转角度参数,用于将所有顶点绕 Z 轴逆时针旋转指定角度。该函数内部先使用 `rotation_matrix` 函数计算旋转矩阵,然后依次旋转每个三维顶点,并生成新的坐标点替换原有的点。最后,该代码进行了一系列测试,展示了三维顶点旋转的效果,并使用 `matplotlib` 库绘制了新的三维顶点。