我正在尝试使用 vispy 按键盘上的“z”来旋转立方体。
但是,我希望每次按下“z”时那个立方体都会旋转,但现在情况并非如此:它只会在我第一次按下它时旋转,然后当我再次按下它时,什么也没有发生......
这是代码。
from vispy import app, scene, geometry
import numpy as np
class MonCanvas(scene.SceneCanvas):
def on_key_press(self,event):
global cube1, cube2, c1data, c2data
if event.text == 'a':
c1data.set_face_colors([[0,0,1,1],[0,0,1,1],[0,1,0,1],[0,1,0,1],[1,1,1,1],[1,1,1,1],[1,1,0,1],[1,1,0,1],[1,0,0,1],[1,0,0,1],[1,0.5,0,1],[1,0.5,0,1]])
cube1.mesh_data_changed()
if event.text == 'z':
rot1 = scene.transforms.MatrixTransform()
rot1.rotate(90,(0,0,1))
cube2.transform = rot1
fenetre = MonCanvas(title="Fenêtre principale", size=(2000,1000), keys="interactive")
view = fenetre.central_widget.add_view()
view.camera = 'turntable'
view.camera.distance = 10
c1data = geometry.MeshData(vertices = np.array([[0.5,0.5,-0.5],[0.5,-0.5,-0.5],[-0.5,0.5,-0.5],[-0.5,-0.5,-0.5],[0.5,0.5,0.5],[0.5,-0.5,0.5],[-0.5,0.5,0.5],[-0.5,-0.5,0.5]]), edges = np.array([[0,1],[0,2],[0,4],[3,1],[3,2],[3,7],[5,1],[5,4],[5,7],[6,2],[6,4],[6,7]]), faces = np.array([[1,2,3],[0,1,2],[5,6,7],[4,5,6],[0,1,5],[0,5,4],[2,3,7],[2,7,6],[1,3,7],[1,7,5],[0,2,6],[0,6,4]]))
c1data.set_face_colors([[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1],[0,0,1,1]])
cube1 = scene.visuals.Mesh(meshdata = c1data)
view.add(cube1)
c2data = geometry.MeshData(vertices = np.array([[0.5,0.5,0.5],[0.5,-0.5,0.5],[-0.5,0.5,0.5],[-0.5,-0.5,0.5],[0.5,0.5,1.5],[0.5,-0.5,1.5],[-0.5,0.5,1.5],[-0.5,-0.5,1.5]]), edges = np.array([[0,1],[0,2],[0,4],[3,1],[3,2],[3,7],[5,1],[5,4],[5,7],[6,2],[6,4],[6,7]]), faces = np.array([[1,2,3],[0,1,2],[5,6,7],[4,5,6],[0,1,5],[0,5,4],[2,3,7],[2,7,6],[1,3,7],[1,7,5],[0,2,6],[0,6,4]]))
c2data.set_face_colors([[0,0,1,1],[0,0,1,1],[0,1,0,1],[0,1,0,1],[1,1,1,1],[1,1,1,1],[1,1,0,1],[1,1,0,1],[1,0,0,1],[1,0,0,1],[1,0.5,0,1],[1,0.5,0,1]])
cube2 = scene.visuals.Mesh(meshdata = c2data)
view.add(cube2)
fenetre.show()
app.run()
在此先感谢您的帮助!
变换应用于GPU内部
MeshVisual
的坐标。他们不会修改 MeshVisual
内的坐标。所以当你跑步时:
rot1 = scene.transforms.MatrixTransform()
rot1.rotate(90,(0,0,1))
cube2.transform = rot1
你告诉 vispy 和 GPU 获取
cube2
的坐标并在使用/绘制它们之前将它们旋转 90 度。换句话说,您告诉它要应用什么转换,但您并没有执行该转换。所以,你每次都需要把那个 90 加上 90。所以你的一系列旋转将是 X,然后在第一个z
之后它们将是 X + 90,然后是 X + 180,然后是 X + 270,依此类推。但应该有更简单的方法来做到这一点......
看起来你可以做
cube2.transform.rotate(90)
,这将修改现有的转换。这具有不创建新变换对象的额外性能优势,因为这样做需要为每个旋转重新编译着色器代码,这会更慢。所以这样做对我有用:
if event.text == 'z':
cube2.transform.rotate(90, (0, 0, 1))
但是您需要确保在创建
cube2
后将初始变换设置为 MatrixTransform 否则 cube2.transform
将不是可以旋转的矩阵变换:
cube2 = scene.visuals.Mesh(meshdata = c2data)
cube2.transform = scene.transforms.MatrixTransform()
view.add(cube2)