在Python中旋转一个三维对象

4
我已经完成了两个立方体的3D绘图。但是现在我想让它旋转,那么我该如何旋转内部的立方体?我希望水平旋转90度!以下是代码:

enter image description here

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("auto")
ax.set_autoscale_on(True)


#dibujar cubo
r = [-10, 10]
 for s, e in combinations(np.array(list(product(r,r,r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s,e), color="b")


#dibujar punto
#ax.scatter([0],[0],[0],color="g",s=100)

d = [-2, 2]
for s, e in combinations(np.array(list(product(d,d,d))), 2):
    if np.sum(np.abs(s-e)) == d[1]-d[0]:
        ax.plot3D(*zip(s,e), color="g")

plt.show()
1个回答

10

由于您正在单独绘制每个顶点,因此我认为您需要对每个顶点应用旋转。 3D旋转可能很困惑,有许多方法来定义这种旋转,取决于您想要如何旋转,这将决定您选择哪种旋转方式。

您表明希望进行水平旋转,在这样一个3D图像中,不清楚什么是水平旋转,如果我误解了您的意思,请原谅我,假设您想以角度绕z轴旋转。

要旋转长度为3的向量p,我们保持第三分量恒定,并对其他两个分量进行旋转。 这最好通过矩阵乘法理解,但我将解释留给Wolfram页面

p_rotated_x = p_x * sin(theta) - p_y * sin(theta)
p_rotated_y = p_x * sin(theta) + p_y * cos(theta)
p_rotate_z = p_z

在上面链接中应用R_z旋转矩阵后,这是旋转的组件。导入一些三角函数后将其应用于您的代码。

from numpy import sin, cos
theta = np.radians(30)
for s, e in combinations(np.array(list(product(d,d,d))), 2):
    if np.sum(np.abs(s-e)) == d[1]-d[0]:
        s_rotated = [s[0] * cos(theta) - s[1] * sin(theta), 
                     s[0] * sin(theta) + s[1] * cos(theta),
                     s[2]]
        e_rotated = [e[0] * cos(theta) - e[1] * sin(theta), 
                     e[0] * sin(theta) + e[1] * cos(theta),
                     e[2]]      
        ax.plot3D(*zip(s_rotated,e_rotated), color="g")

plt.show()

这将会给出: enter image description here 请注意,角度由三角函数指定,需要转换为弧度。
这是一个相当简单的旋转,实现方式有些简单。我承认这可以得到改进,但基本思想已经在那里。如果您想要使用更复杂的方法进行旋转,我建议阅读Euler angles,这是理解3D旋转的一种直观方式(至少对我来说是这样)。

1
你好!现在我想在立方体的每个面上画箭头,你有什么办法可以实现吗? - Diego Martínez Giardini
你需要打开另一个问题,我建议你先试一试,如果遇到困难,请发布你的尝试和你卡住的地方的描述。如果你阅读了这篇文章,我认为你可以轻松完成这个任务:https://dev59.com/3Wgu5IYBdhLWcg3ws5BC - Greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接