Rotating Cube

Smallest 3D scene.

▶ Run in browser

Tags: 3d

A 3D scene needs two nodes: a Camera3D to look through and something to see. Here that is a MeshInstance3D, which pairs geometry (Mesh.box(), a unit cube) with a Material giving its colour and roughness. Both are constructor keywords, as is the camera’s position, look_at target and fov in degrees.

Motion is ordinary Python in on_update(dt): each frame the cube turns by rotate_y and rotate_x, in radians, scaled by dt so the speed (1 and 0.5 radians per second) does not depend on the frame rate.

Source

 1"""Rotating Cube: Smallest 3D scene.
 2
 3A 3D scene needs two nodes: a `Camera3D` to look through and something to
 4see. Here that is a `MeshInstance3D`, which pairs geometry (`Mesh.box()`, a
 5unit cube) with a `Material` giving its colour and roughness. Both are
 6constructor keywords, as is the camera's `position`, `look_at` target and
 7`fov` in degrees.
 8
 9Motion is ordinary Python in `on_update(dt)`: each frame the cube turns by
10`rotate_y` and `rotate_x`, in radians, scaled by `dt` so the speed (1 and 0.5
11radians per second) does not depend on the frame rate.
12"""
13
14from simvx.core import Camera3D, Material, Mesh, MeshInstance3D, Node
15from simvx.graphics import App
16
17
18class RotatingCube(Node):
19    def on_ready(self):
20        self.add_child(Camera3D(position=(0, 2, 5), look_at=(0, 0, 0), fov=60.0))
21        self.cube = self.add_child(
22            MeshInstance3D(mesh=Mesh.box(), material=Material(colour=(0.2, 0.6, 1.0, 1.0), roughness=0.4))
23        )
24
25    def on_update(self, dt):
26        self.cube.rotate_y(1.0 * dt)
27        self.cube.rotate_x(0.5 * dt)
28
29
30if __name__ == "__main__":
31    App(title="Rotating Cube", width=800, height=600).run(RotatingCube())