Created
November 12, 2023 14:00
-
-
Save mafshin/b5db03d08cda013a71f143f3537716f7 to your computer and use it in GitHub Desktop.
3D Scene NiceGUI Move Car in Road
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 math | |
from nicegui import app, ui | |
class SceneState(): | |
def __init__(self) -> None: | |
self.stage = '' | |
self.road_parts = [] | |
self.light_poles = [] | |
self.car = None | |
self.refresh_rate = 20 | |
state = SceneState() | |
def play(): | |
timer.active = not timer.active | |
def add_light_poles(): | |
state.stage = 'ADD_LIGHT_POLES' | |
play() | |
def add_road_part(x, y, z): | |
state.road_parts.append(scene.box(20,2, 1).move(x, y, z).material('#b7b1ae')) | |
def add_light_pole(x, y, z): | |
with scene.group() as light_pole: | |
scene.cylinder(1.5, 2, 1, radial_segments=20).rotate(math.radians(90), 0, 0).move(0, 0, 0.5).material('gray') | |
scene.cylinder(0.5, 0.5, 10).rotate(math.radians(90), 0, 0).move(0, 0, 5).material('lightgray') | |
scene.sphere(1).move(0, 0, 11).material('yellow') | |
scene.spot_light('yellow', intensity=1, distance=20, angle=math.pi/2).move(0, 0, 11) | |
light_pole.move(x, y, 0.5) | |
state.light_poles.append(light_pole) | |
def add_road(): | |
state.stage = 'ADD_ROAD' | |
play() | |
def update_scene(): | |
movement = 10 | |
delta = movement / state.refresh_rate | |
ui.notify(f'update_scene in stage: {state.stage}') | |
if(state.stage == 'ADD_ROAD' and len(state.road_parts) < 20): | |
y = len(state.road_parts) * 2.1 | |
add_road_part(0, y, 0) | |
elif(state.stage == 'ADD_LIGHT_POLES' and len(state.light_poles) < 5): | |
y = len(state.light_poles) * 10 | |
add_light_pole(0, y, 0) | |
elif state.stage == 'MOVE_CAR' and state.car.y < 30: | |
y = state.car.y | |
state.car.move(state.car.x, state.car.y + delta, state.car.z) | |
else: | |
timer.active = False | |
def add_car(): | |
state.car = scene.stl('assets/Shiny Amberis-Jofo.stl').material('silver').scale(0.1).move(5, 5, 0.5).rotate(0, 0, math.radians(180)) | |
def move_car(): | |
state.stage = 'MOVE_CAR' | |
state.refresh_rate = 60 | |
timer.interval = 1/state.refresh_rate | |
play() | |
with ui.row(): | |
ui.button('Play/Pause', on_click=play) | |
ui.button('Add Road', on_click=add_road) | |
ui.button('Add Light Poles', on_click=add_light_poles) | |
ui.button('Add Car', on_click=add_car) | |
ui.button('Move Car', on_click=move_car) | |
timer = ui.timer(1/state.refresh_rate, update_scene, active=False) | |
app.add_static_files('/assets', 'assets') | |
with ui.scene().classes('w-full h-64') as scene: | |
scene.sphere(radius=0.5).material('red') | |
scene.camera.y = -20 | |
scene.camera.z = 20 | |
ui.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment