Created
November 4, 2023 13:55
-
-
Save mafshin/db316ee30fbd7653256146a16ba28754 to your computer and use it in GitHub Desktop.
3D Scene with boxes with NiceGUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from nicegui import events, ui | |
from nicegui.events import KeyEventArguments | |
def handle_click(e: events.SceneClickEventArguments): | |
hit = e.hits[0] | |
name = hit.object_name or hit.object_id | |
notify(f'You clicked on the {name} at ({hit.x:.2f}, {hit.y:.2f}, {hit.z:.2f})') | |
clicked_box = next(filter(lambda x: x.name == name, scene_state.boxes), None) | |
if clicked_box: | |
if scene_state.selected_box: | |
scene_state.selected_box.material('white') | |
scene_state.selected_box = clicked_box | |
scene_state.selected_box.material('yellow') | |
def notify(message): | |
ui.notify(message, position='bottom-left') | |
class SceneState(): | |
def __init__(self) -> None: | |
self.boxes = [] | |
self.selected_box = None | |
scene_state = SceneState() | |
def handle_key(e: KeyEventArguments): | |
if e.modifiers.shift: | |
if e.key.arrow_up: | |
notify('going up in z') | |
move_box(0, 0, 1) | |
elif e.key.arrow_down: | |
notify('going down in z') | |
move_box(0, 0, -1) | |
else: | |
if e.key.arrow_left: | |
notify('going left') | |
move_box(-1, 0, 0) | |
elif e.key.arrow_right: | |
notify('going right') | |
move_box(1, 0, 0) | |
elif e.key.arrow_up: | |
notify('going up') | |
move_box(0, 1, 0) | |
elif e.key.arrow_down: | |
notify('going down') | |
move_box(0, -1, 0) | |
def move_box(movement_x, movement_y, movement_z): | |
box = scene_state.selected_box | |
new_x = box.x + movement_x | |
new_y = box.y + movement_y | |
new_z = box.z + movement_z | |
box.move(x = new_x, y = new_y, z = new_z) | |
def add_random_boxes(): | |
random_number = random.randint(1, 10) | |
for x in range(random_number): | |
random_x = random.randint(-10, 10) | |
random_y = random.randint(-10, 10) | |
box_number = len(scene_state.boxes) + 1 | |
box = scene.box().with_name(f'Box {box_number}').material().move(x = random_x, y = random_y, z = 0.5) | |
scene_state.boxes.append(box) | |
keyboard = ui.keyboard(on_key=handle_key) | |
ui.label('Key events can be caught globally by using the keyboard element.') | |
ui.checkbox('Track key events', value=True).bind_value_to(keyboard, 'active') | |
ui.button('Random Boxes', on_click=add_random_boxes) | |
with ui.scene(on_click=handle_click).classes('w-full h-64') as scene: | |
first_box = scene.box().with_name('Box 1').material().move(x = 0.5, y = 0.5, z = 0.5) | |
scene_state.boxes.append(first_box) | |
ui.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment