### Basic Ursina App Setup Source: https://www.ursinaengine.org/api_reference.html A minimal example to initialize the Ursina engine and display a white cube. This is a fundamental setup for any Ursina application. ```python from ursina import * app = Ursina() Entity(model='quad', texture='white_cube') app.run() ``` -------------------------------- ### Basic Scene Setup with Sky and EditorCamera Source: https://www.ursinaengine.org/api_reference.html This example demonstrates a basic scene setup using Ursina, including initializing the engine, creating a Skybox, and setting up an EditorCamera for debugging. The EditorCamera is configured to ignore scroll events on UI elements. ```python from ursina import Ursina, Sky, load_model, color, Text, window, Button app = Ursina(vsync=False, use_ingame_console=True) ''' Simple camera for debugging. Hold right click and move the mouse to rotate around point. ''' sky = Sky() e = Entity(model=load_model('cube', use_deepcopy=True), color=color.white, collider='box') e.model.colorize() ground = Entity(model='plane', scale=32, texture='white_cube', texture_scale=(32,32), collider='box') box = Entity(model='cube', collider='box', texture='white_cube', scale=(10,2,2), position=(2,1,5), color=color.light_gray) b = Button(position=window.top_left, scale=.05) ec = EditorCamera(ignore_scroll_on_ui=True) rotation_info = Text(position=window.top_left) def update(): rotation_info.text = str(int(ec.rotation_y)) + '\n' + str(int(ec.rotation_x)) app.run() ``` -------------------------------- ### Initialize Ursina Application Source: https://www.ursinaengine.org/api_reference.html Basic setup for an Ursina application. This example initializes the Ursina engine with specific settings and defines a custom input handler. ```python from ursina import * app = **Ursina**(development_mode=False, use_ingame_console=True) def input(key): print(key) app.run() ``` -------------------------------- ### Camera Setup and Shader Application Source: https://www.ursinaengine.org/api_reference.html Shows how to configure camera properties like orthographic projection and apply post-processing shaders. This example sets the camera to orthographic mode and applies a grayscale shader. ```python from ursina import * from ursina import Ursina, camera, Entity, EditorCamera app = Ursina() camera.orthographic = True e = Entity() e.model = 'quad' e.color = color.random_color() e.position = (-2, 0, 10) e = Entity() e.model = 'quad' e.color = color.random_color() e.position = (2, 0, 10) e = Entity() e.model = 'quad' e.color = color.random_color() e.position = (0, 0, 40) EditorCamera() from ursina.shaders import camera_grayscale_shader camera.shader = camera_grayscale_shader app.run() ``` -------------------------------- ### Starting a Conversation Source: https://www.ursinaengine.org/api_reference.html Example of how to initialize and start a conversation using the Conversation prefab with a predefined dialogue string. ```APIDOC ## Example Usage ### Description This example demonstrates how to set up a basic conversation with a `variables_object` and a multi-line dialogue string. It shows how to start the conversation and handle basic input. ### Code ```python from ursina import * from textwrap import dedent app = Ursina() # Define variables for the conversation variables = Empty( evil=0, chaos=0, bar_mission_solved=False, ) # Initialize the Conversation prefab conversation = Conversation(variables_object=variables) # Define the conversation dialogue convo = dedent(''' I'm looking for my sister. Can you help me find her, please? I haven't seen her in days! Who know what could've happened!? I'm worried. Will you help me? * Yes, of course. This can be a dangerous city. Oh no! Do you think something happened to her? What should I do?! * She's probably fine. She can handle herself. You're right. I'm still worried though. * Don't worry, I'll look for her. * Maybe. (stats.chaos += 1) Help me look for her, please! *runs off* * I'm sorry, but I don't have time right now. (evil += 1) A true friend wouldn't say that. * I know where she is! (if bar_mission_solved) Really? Where? * I saw her on a ship by the docks, it looked like they were ready to set off. Thank you! *runs off* ''') # Start the conversation conversation.start_conversation(convo) # Define input handling def input(key): if key == 'space': print(variables.evil) Sprite('shore', z=1) app.run() ``` ### Notes - The `dedent` function is used to clean up the multi-line string formatting. - The `Empty` class from Ursina is used to create a simple object to hold variables. - The `(stats.chaos += 1)` and `(evil += 1)` syntax within the dialogue string indicates how variables can be modified. - The `(if bar_mission_solved)` syntax shows conditional dialogue branching. ``` -------------------------------- ### Triplanar Shader Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to use the triplanar_shader with different textures and scales on various primitive shapes. Includes setting shader inputs and editor camera setup. ```python from ursina import * from ursina.prefabs.primitives import * app = Ursina() window.color=color.black shader = triplanar_shader a = Draggable(parent=scene, model='cube', shader=shader, texture=load_texture('brick'), plane_direction=Vec3(0,1,0)) t = load_texture('brick')._texture print('------', type(t)) a.set_shader_input('side_texture', load_texture('brick')) b = AzureSphere(shader=shader, rotation_y=180, x=3, texture='grass') b.texture.filtering = False GrayPlane(scale=10, y=-2, texture='shore') b.set_shader_input('side_texture', load_texture('brick')) Sky(color=color.light_gray) EditorCamera() def set_side_texture_scale(): value = side_texture_scale_slider.value b.set_shader_input('side_texture_scale', Vec2(value, value)) a.set_shader_input('side_texture_scale', Vec2(value, value)) side_texture_scale_slider = Slider(text='side_texture_scale', min=0, max=10, default=1, dynamic=True, on_value_changed=set_side_texture_scale) def update(): b.rotation_y += 1 b.rotation_x += 1 app.run() ``` -------------------------------- ### Button Example Usage Source: https://www.ursinaengine.org/api_reference.html Provides practical examples of creating and using buttons, including assigning click functions, tooltips, and updating text. ```APIDOC ```python from ursina import * app = Ursina() # Example 1: Basic button with text and click function Button.default_color = color.red b = Button(model='quad', scale=.05, x=-.5, color=color.lime, text='text scale\ntest', text_size=.5, text_color=color.black) b.text_size = .5 b.on_click = Sequence(Wait(.5), Func(print, 'aaaaaa')) # Example 2: Button in UI with default color b = Button(parent=camera.ui, text='hello world!', scale=.25) # Example 3: Button with icon and custom text origin Button.default_color = color.blue b = Button(text='hello world!', icon='sword', scale=.25, text_origin=(-.5,0), x=.5) b.on_click = application.quit # assign a function to the button. b.tooltip = Tooltip('exit') # Example 4: Button as a child of another entity par = Entity(parent=camera.ui, scale=.2, y=-.2) b = Button(parent=par, text='test', scale_x=1, origin=(-.5,.5)) b.text ='new text' print(b.text_entity) # Example 5: Button with sounds Button(text='sound', scale=.2, position=(-.25,-.2), color=color.pink, highlight_sound='blip_1', pressed_sound=Audio('coin_1', autoplay=False)) Text('Text size\nreference', x=.15) def input(key): if key == 'd': scene.clear() if key == 'space': b.text = 'updated text' app.run() ``` ``` -------------------------------- ### Basic Ursina App Setup Source: https://www.ursinaengine.org/ This snippet shows the basic setup for an Ursina application, including creating an entity, defining a click action, and running the app with editor camera controls. ```python from ursina import * app = Ursina() cube = Entity(model='cube', color=hsv(300,1,1), scale=2, collider='box') def spin(): cube.animate('rotation_y', cube.rotation_y+360, duration=2, curve=curve.in_out_expo) cube.on_click = spin EditorCamera() # add camera controls for orbiting and moving the camera app.run() ``` -------------------------------- ### Basic Ursina App with Texture Source: https://www.ursinaengine.org/api_reference_v8_2_0/texture_importer.html A simple example demonstrating how to create an Ursina application and display an entity with a texture. This requires the Ursina library to be installed. ```python from ursina import * app = Ursina() Entity(model='quad', texture='white_cube') app.run() ``` -------------------------------- ### Install All Optional Dependencies Source: https://www.ursinaengine.org/installation.html Install all optional dependencies for Ursina at once using pip. ```python pip install ursina[extras] ``` -------------------------------- ### Example Usage Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to use the mouse API, including locking the cursor and printing mouse velocity. ```APIDOC ## Example Usage ### Description This example shows how to initialize Ursina, create a button, handle spacebar input to toggle mouse lock, print mouse velocity, and display a cursor. ### Code ```python from ursina import * from ursina import Ursina, Button, mouse app = Ursina() Button(parent=scene, text='a') def input(key): if key == 'space': mouse.locked = not mouse.locked print(mouse.velocity) Cursor() app.run() ``` ``` -------------------------------- ### Slider Initialization and Usage Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to create and use Slider and ThinSlider prefabs. It shows setting minimum, maximum, default values, step increments, and callback functions for value changes. The example also illustrates dynamic updates and label positioning. ```python app = Ursina() box = Entity(model='cube', origin_y=-.5, scale=1, color=color.orange) def scale_box(): box.scale_y = slider.value print(thin_slider.value) slider = Slider(0, 20, default=10, height=Text.size*3, y=-.4, step=1, on_value_changed=scale_box, vertical=True) thin_slider = ThinSlider(text='height', dynamic=True, on_value_changed=scale_box) thin_slider.label.origin = (0,0) thin_slider.label.position = (.25, -.1) app.run() ``` -------------------------------- ### Application Setup and Run Source: https://www.ursinaengine.org/rubiks_cube.html Configures the window properties, sets up an editor camera for navigation, and runs the Ursina application to display the Rubik's Cube. ```python window.color = color._16 EditorCamera() app.run() ``` -------------------------------- ### TextField Example Source: https://www.ursinaengine.org/api_reference.html Example usage of the TextField prefab. ```APIDOC ## TextField Example ### Description Demonstrates how to create and use a TextField with initial text and custom input handling. ### Code ```python from ursina import Ursina, window, Button, color from textwrap import dedent app = Ursina(vsync=60) window.color = color.hsv(0, 0, .1) Button.default_color = color._20 window.color = color._25 te = TextField(max_lines=30, scale=1, register_mouse_input = True, text='1234') te.text = dedent(''' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sapien tellus, venenatis sit amet ante et, malesuada porta risus. Etiam et mi luctus, viverra urna at, maximus eros. Sed dictum faucibus purus, nec rutrum ipsum condimentum in. Mauris iaculis arcu nec justo rutrum euismod. Suspendisse dolor tortor, congue id erat sit amet, sollicitudin facilisis velit. Aliquam sapien tellus, venenatis sit amet ante et, malesuada porta risus. Etiam et mi luctus, viverra urna at, maximus eros. Sed dictum faucibus purus, nec rutrum ipsum condimentum in. Mauris iaculis arcu nec justo rutrum euismod. Suspendisse dolor tortor, congue id erat sit amet, sollicitudin facilisis velit. '''*30 )[1:] te.render() def input(key): if key == '3': te.input('scroll down') app.run() ``` ``` -------------------------------- ### Basic Ursina Audio Example Source: https://www.ursinaengine.org/api_reference_v8_2_0/ursinastuff.html Demonstrates initializing Ursina, playing a sine wave audio, and destroying the audio entity after a delay. ```python copy from ursina import * app = Ursina() a = Audio('sine') a.play() destroy(a, delay=1) app.run() ``` -------------------------------- ### Color Examples Source: https://www.ursinaengine.org/api_reference_v8_2_0/color.html Example usage of the color module. ```APIDOC ## Examples ```python from ursina import * from ursina import Button, Entity, Quad, Ursina, color, grid_layout from ursina.ursinastuff import _test app = Ursina() _test(hsv(30,1,1) == color.orange) _test(color.brightness(color.blue) == 1.0) _test(color.red.rgb == (1.0, 0.0, 0.0)) _test(color.red.rgba == (1.0, 0.0, 0.0, 1.0)) p = Entity(x=-2) for key in color.colors: print(key) b = Button(parent=p, model=Quad(0), color=color.colors[key], text=key) b.text_entity.scale *= .5 grid_layout(p.children, max_x=8) for name in ('r', 'g', 'b', 'h', 's', 'v', 'brightness'): print(name + ':', getattr(color.random_color(), name)) e = Entity(model='cube', color=color.lime) print(e.color.name) print('rgb to hex:', color.rgb_to_hex(*color.blue)) e.color = color.rgba32(1,2,3) app.run() ``` ``` -------------------------------- ### Level Generation Setup Source: https://www.ursinaengine.org/platformer_tutorial.html Prepares a `Mesh` for the level and an `Entity` to parent it. This setup is used to build the level geometry from pixel data. ```python quad = load_model('quad', use_deepcopy=True) level_parent = Entity(model=Mesh(vertices=[], uvs=[]), texture='white_cube') ``` -------------------------------- ### Environment Setup Source: https://www.ursinaengine.org/fps.html Configures the sun's direction and sets up a skybox for the game environment. ```python sun = DirectionalLight() sun.look_at(Vec3(1,-1,-1)) Sky() ``` -------------------------------- ### Pixel Editor Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to use the PixelEditor prefab to create a drawing tool, similar to a level editor. This example initializes a new texture and allows modification. ```python app = Ursina(borderless=False) ''' pixel editor example, it's basically a drawing tool. can be useful for level editors and such here we create a new texture, but can also give it an existing texture to modify. ''' from PIL import Image t = Texture(Image.new(mode='RGBA', size=(32,32), color=(0,0,0,1))) from ursina.prefabs.grid_editor import PixelEditor editor = PixelEditor(parent=scene, texture=load_texture('brick'), scale=10) camera.orthographic = True camera.fov = 15 EditorCamera(rotation_speed=0) from ursina.prefabs.grid_editor import ASCIIEditor ASCIIEditor(x=0, scale=.1) app.run() ``` -------------------------------- ### Example Usage Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to create terrain entities using both heightmap textures and lists of height values, and how to dynamically update and regenerate the terrain. ```APIDOC ## Example Usage ### Terrain from Heightmap Texture ```python app = Ursina() # Terrain using an RGB texture as input terrain_from_heightmap_texture = Entity(model=Terrain('heightmap_1', skip=8), scale=(40, 5, 20), texture='heightmap_1') ``` ### Terrain from Height Values List ```python # Get height values from the previous terrain hv = terrain_from_heightmap_texture.model.height_values.tolist() # Create terrain from the list of height values terrain_from_list = Entity(model=Terrain(height_values=hv), scale=(40, 5, 20), texture='heightmap_1', x=40) # Add a wireframe cube to visualize bounds terrain_bounds = Entity(model='wireframe_cube', origin_y=-.5, scale=(40, 5, 20), color=color.lime) ``` ### Dynamic Terrain Generation ```python def input(key): if key == 'space': # Randomize the terrain height values terrain_from_list.model.height_values = [[random.uniform(0, 255) for a in column] for column in terrain_from_list.model.height_values] # Regenerate the terrain mesh terrain_from_list.model.generate() EditorCamera(rotation_x=90) camera.orthographic = True Sky() player = Entity(model='sphere', color=color.azure, scale=.2, origin_y=-.5) def update(): # Player movement direction = Vec3(held_keys['d'] - held_keys['a'], 0, held_keys['w'] - held_keys['s']).normalized() player.position += direction * time.dt * 8 # Raycast to terrain to set player's y position y = terraincast(player.world_position, terrain_from_list, terrain_from_list.model.height_values) if y is not None: player.y = y app.run() ``` ``` -------------------------------- ### Create and Configure a ButtonList Source: https://www.ursinaengine.org/api_reference.html Shows how to create a ButtonList with custom functions assigned to buttons. Includes examples of dynamic updates to the button dictionary and selecting buttons. ```python from ursina import Ursina, Func app = Ursina() defaul = Func(print, 'not yet implemented') def test(a=1, b=2): print('------:', a, b) button_dict = {} for i in range(6, 20): button_dict[f'button {i}'] = Func(print, i) bl = ButtonList(button_dict, font='VeraMono.ttf', button_height=1.5, popup=0, clear_selected_on_enable=False) def input(key): if key == 'space': bl.button_dict = { 'one' : None, 'two' : defaul, 'tree' : Func(test, 3, 4), 'four' : Func(test, b=3, a=4), } if key == 'o': bl.enabled = True bl.selected = 'button 7' bl.button_dict = {} app.run() ``` -------------------------------- ### String Utility Examples Source: https://www.ursinaengine.org/api_reference.html Demonstrates the usage of string conversion and variable printing utilities. Useful for debugging and data formatting. ```python print(camel_to_snake('CamelToSnake')) print(snake_to_camel('snake_to_camel')) printvar('test') ``` -------------------------------- ### Install Ursina Development Version from GitHub (Clone) Source: https://www.ursinaengine.org/installation.html Clone the Ursina GitHub repository and install it as a development version. This is recommended if you plan to edit the source code. Ensure Git is installed. ```python git clone https://github.com/pokepetter/ursina.git python -m pip install --editable . ``` -------------------------------- ### TextField Initialization and Usage Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to initialize a TextField with a large amount of text and simulate scrolling. This example shows setting up the Ursina app, customizing UI elements, and using the TextField's text input and rendering capabilities. It also includes a custom input handler for scrolling. ```python from ursina import Ursina, window, Button app = Ursina(vsync=60) window.color = color.hsv(0, 0, .1) Button.default_color = color._20 window.color = color._25 te = TextField(max_lines=30, scale=1, register_mouse_input = True, text='1234') from textwrap import dedent te.text = dedent(''' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sapien tellus, venenatis sit amet ante et, malesuada porta risus. Etiam et mi luctus, viverra urna at, maximus eros. Sed dictum faucibus purus, nec rutrum ipsum condimentum in. Mauris iaculis arcu nec justo rutrum euismod. Suspendisse dolor tortor, congue id erat sit amet, sollicitudin facilisis velit. Aliquam sapien tellus, venenatis sit amet ante et, malesuada porta risus. Etiam et mi luctus, viverra urna at, maximus eros. Sed dictum faucibus purus, nec rutrum ipsum condimentum in. Mauris iaculis arcu nec justo rutrum euismod. Suspendisse dolor tortor, congue id erat sit amet, sollicitudin facilisis velit. '''*30 )[1:] te.render() def input(key): if key == '3': te.input('scroll down') app.run() ``` -------------------------------- ### TrailRenderer Example Source: https://www.ursinaengine.org/api_reference.html Shows how to implement a TrailRenderer to create visual trails behind an entity. This example sets up a player entity with a trail and updates the player's position based on mouse movement. Trails can be toggled on/off. ```python app = Ursina(vsync=False) window.color = color.black mouse.visible = False player = Entity(z=1) player.graphics = Entity(parent=player, scale=.1, model='circle') pivot = Entity() trail_renderers = [] for i in range(1): tr = TrailRenderer(size=[1,1], segments=8, min_spacing=.05, fade_speed=0, parent=player, color_gradient=[color.magenta, color.cyan.tint(-.5), color.clear]) trail_renderers.append(tr) def update(): player.position = lerp(player.position, mouse.position*10, time.dt*4) def input(key): if key == 'escape': for e in trail_renderers: e.enabled = not e.enabled if key == 'space': destroy(pivot) EditorCamera() Entity(model=Grid(8,8), rotation_x=90, color=color.gray, y=-3, scale=8) app.run() ``` -------------------------------- ### Gradient Generation Examples Source: https://www.ursinaengine.org/api_reference_v8_2_0/ursinamath.html Provides test cases for the make_gradient function, demonstrating its use with colors and numerical values. ```python if __name__ == '__main__': _test(make_gradient({'0':color.hex('#ff0000ff'), '2':color.hex('#ffffffff')}) == [ color.hex('#ff0000ff'), lerp(color.hex('#ff0000ff'), color.hex('#ffffffff'), .5), color.hex('#ffffffff'), ]) _test(make_gradient({'0':color.hex('#ff0000ff'), '4':color.hex('#ffffffff')}) == [ color.hex('#ff0000ff'), lerp(color.hex('#ff0000ff'), color.hex('#ffffffff'), .25), lerp(color.hex('#ff0000ff'), color.hex('#ffffffff'), .5), lerp(color.hex('#ff0000ff'), color.hex('#ffffffff'), .75), color.hex('#ffffffff'), ]) _test(make_gradient({'0':16, '2':0}) == [16, 8, 0]) _test(make_gradient({'6':0, '8':8}) == [0, 4, 8]) ``` -------------------------------- ### DropdownMenu Creation Example Source: https://www.ursinaengine.org/api_reference.html Illustrates how to create a nested DropdownMenu with multiple levels of options. Each DropdownMenuButton can contain text or another DropdownMenu. ```python from ursina.prefabs.dropdown_menu import DropdownMenu, DropdownMenuButton app = Ursina() DropdownMenu('File', buttons=( DropdownMenuButton('New'), DropdownMenuButton('Open'), DropdownMenu('Reopen Project', buttons=( DropdownMenuButton('Project 1'), DropdownMenuButton('Project 2'), )), DropdownMenuButton('Save'), DropdownMenu('Options', buttons=( DropdownMenuButton('Option a'), DropdownMenuButton('Option b'), )), DropdownMenuButton('Exit'), )) app.run() ``` -------------------------------- ### Transition Shader Example Source: https://www.ursinaengine.org/api_reference.html Applies a transition shader to an entity, allowing for visual effects like cutoffs. Requires the 'transition_shader' to be loaded. ```python from ursina import * app = Ursina() window.color = color._16 Texture.default_filtering = 'bilinear' e = Entity(model='quad', shader=transition_shader, scale=5, cutoff=0, texture='sword_slash', color=color.azure ) mask = load_texture('sword_slash') e.set_shader_input('mask_texture', mask) EditorCamera() min_cutoff_slider = Slider(0, 1, dynamic=True, y=-.4) def on_value_changed(): e.set_shader_input('min_cutoff', min_cutoff_slider.value) min_cutoff_slider.on_value_changed = on_value_changed max_cutoff_slider = Slider(0, 1, default=1, dynamic=True, y=-.45) def on_value_changed(): e.set_shader_input('max_cutoff', max_cutoff_slider.value) max_cutoff_slider.on_value_changed = on_value_changed def input(key): if key == 'space': e.cutoff = 0 e.animate('cutoff', 1, duration=.1, curve=curve.linear, delay=.05) app.run() ``` -------------------------------- ### Basic Mouse Input and Locking Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to toggle mouse locking with the spacebar and print mouse velocity. Requires Ursina and Button imports. ```python from ursina import * from ursina import Ursina, Button, mouse app = Ursina() Button(parent=scene, text='a') def input(key): if key == 'space': mouse.locked = not mouse.locked print(mouse.velocity) Cursor() app.run() ``` -------------------------------- ### Basic Transition Shader Setup Source: https://www.ursinaengine.org/api_reference_v8_2_0/transition_shader.html Demonstrates how to set up an entity with the transition_shader, load textures, and control shader inputs like mask_texture, min_cutoff, and max_cutoff. Includes interactive sliders for cutoff values and a spacebar trigger for animation. ```python from ursina import * app = Ursina() window.color = color._16 Texture.default_filtering = 'bilinear' e = Entity(model='quad', shader=transition_shader, scale=5, cutoff=0, texture='shore', color=color.azure ) mask = load_texture('shore') e.set_shader_input('mask_texture', mask) EditorCamera() min_cutoff_slider = Slider(0, 1, dynamic=True, y=-.4) def on_value_changed(): e.set_shader_input('min_cutoff', min_cutoff_slider.value) min_cutoff_slider.on_value_changed = on_value_changed max_cutoff_slider = Slider(0, 1, default=1, dynamic=True, y=-.45) def on_value_changed(): e.set_shader_input('max_cutoff', max_cutoff_slider.value) max_cutoff_slider.on_value_changed = on_value_changed def input(key): if key == 'space': e.cutoff = 0 e.animate('cutoff', 1, duration=.1, curve=curve.linear, delay=.05) app.run() ``` -------------------------------- ### Button Initialization and Customization Source: https://www.ursinaengine.org/api_reference.html Demonstrates creating multiple Button instances with various configurations, including text scaling, colors, icons, click actions, and tooltips. It also shows how to update button text and assign sounds. ```python from ursina import * app = Ursina() Button.default_color = color.red b = Button(model='quad', scale=.05, x=-.5, color=color.lime, text='text scale\ntest', text_size=.5, text_color=color.black) b.text_size = .5 b.on_click = Sequence(Wait(.5), Func(print, 'aaaaaa')) b = Button(parent=camera.ui, text='hello world!', scale=.25) Button.default_color = color.blue b = Button(text='hello world!', icon='sword', scale=.25, text_origin=(-.5,0), x=.5) b.on_click = application.quit b.tooltip = Tooltip('exit') par = Entity(parent=camera.ui, scale=.2, y=-.2) b = Button(parent=par, text='test', scale_x=1, origin=(-.5,.5)) b.text ='new text' print(b.text_entity) Button(text='sound', scale=.2, position=(-.25,-.2), color=color.pink, highlight_sound='blip_1', pressed_sound=Audio('coin_1', autoplay=False)) Text('Text size\nreference', x=.15) def input(key): if key == 'd': scene.clear() if key == 'space': b.text = 'updated text' app.run() ``` -------------------------------- ### Custom Cursor Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to create and customize a Cursor prefab with a specific model and scale. The mouse visibility is set to False to use the custom cursor. ```python from ursina import Ursina, Button, scene, Panel, Mesh app = Ursina() Button('button').fit_to_text() camera.orthographic = True camera.fov = 100 cursor = **Cursor**(model=Mesh(vertices=[(-.5,0,0),(.5,0,0),(0,-.5,0),(0,.5,0)], triangles=[(0,1),(2,3)], mode='line', thickness=2), scale=.02) mouse.visible = False app.run() ``` -------------------------------- ### Initialize Ursina Platformer Source: https://www.ursinaengine.org/platformer.html Basic setup for a 2D platformer game using Ursina. Imports necessary modules and initializes the Ursina app. ```python from ursina import * from ursina.prefabs.platformer_controller_2d import PlatformerController2d app = Ursina() window.color = color.light_gray camera.orthographic = True camera.fov = 20 ``` -------------------------------- ### Example: Getting Mouse Position in 3D Source: https://www.ursinaengine.org/api_reference_v8_2_0/mouse.html Demonstrates how to get the mouse's world position and use it to update an object's position in a 3D scene. ```python from ursina import * app = Ursina() cursor_3d = Entity(model='icosphere', scale=.1, color=color.azure) plane = Entity(model='plane', scale=10, collider='box', color=color.light_gray) EditorCamera() def update(): if mouse.world_point: cursor_3d.position = mouse.world_point app.run() ``` -------------------------------- ### Get Mouse Position in 3D Source: https://www.ursinaengine.org/api_reference_v8_2_0/mouse.html This example demonstrates how to get the mouse's 3D world position and use it to update the position of a cursor entity. It requires the EditorCamera to be active for 3D navigation. ```python from ursina import * app = Ursina() cursor_3d = Entity(model='icosphere', scale=.1, color=color.azure) plane = Entity(model='plane', scale=10, collider='box', color=color.light_gray) EditorCamera(rotation_x=30) def update(): if mouse.world_point: cursor_3d.position = mouse.world_point app.run() ``` -------------------------------- ### Initialize Ursina Application Source: https://www.ursinaengine.org/api_reference_v8_2_0/ursina.html Call this at the start of your application to initialize Ursina. Customize window properties like title, icon, and fullscreen mode. ```python from ursina import Ursina app = Ursina(title='My Game', icon='icon.png', fullscreen=True) ``` -------------------------------- ### Button Initialization and Customization Source: https://www.ursinaengine.org/api_reference.html Demonstrates creating and customizing Button instances with different properties like text, scale, color, and text appearance. Shows how to assign click handlers and tooltips. ```python from ursina import * app = Ursina() Button.default_color = color.red b = Button(model='quad', scale=.05, x=-.5, color=color.lime, text='text scale\ntest', text_size=.5, text_color=color.black) b.text_size = .5 b.on_click = Sequence(Wait(.5), Func(print, 'aaaaaa')) b = Button(parent=camera.ui, text='hello world!', scale=.25) Button.default_color = color.blue b = Button(text='hello world!', icon='sword', scale=.25, text_origin=(-.5,0), x=.5) b.on_click = application.quit b.tooltip = Tooltip('exit') par = Entity(parent=camera.ui, scale=.2, y=-.2) b = Button(parent=par, text='test', scale_x=1, origin=(-.5,.5)) b.text ='new text' print(b.text_entity) ``` ```python Button(text='sound', scale=.2, position=(-.25,-.2), color=color.pink, highlight_sound='blip_1', pressed_sound=Audio('coin_1', autoplay=False)) ``` ```python Text('Text size\nreference', x=.15) ``` -------------------------------- ### Normals Shader Example Source: https://www.ursinaengine.org/api_reference.html Shows how to apply the normals_shader to primitive shapes for normal mapping effects. Includes basic setup and animation for spheres. ```python from ursina import * from ursina.prefabs.primitives import * app = Ursina() window.color=color.black shader = normals_shader a = WhiteCube(shader=shader) b = AzureSphere(rotation_y=180, x=3) b.shader = shader GrayPlane(scale=10, y=-2, texture='shore') Sky(color=color.light_gray) EditorCamera() def update(): b.rotation_z += 1 b.rotation_y += 1 b.rotation_x += 1 app.run() ``` -------------------------------- ### Create a Cone Mesh Source: https://www.ursinaengine.org/api_reference.html Creates a Cone mesh with customizable resolution, radius, and height. Includes an example with texture and editor camera setup. ```python from ursina import Ursina, Entity, color, EditorCamera app = Ursina() e = Entity(model=Cone(3), texture='brick') origin = Entity(model='quad', color=color.orange, scale=(.05, .05)) ed = EditorCamera() app.run() ``` -------------------------------- ### Get Bounds of Array3D Source: https://www.ursinaengine.org/api_reference_v8_2_0/array_tools.html Calculates the bounding box of non-default values in an Array3D. Returns a Bounds object with start and end Vec3 points. ```python @property def bounds(self): from ursina.ursinamath import Bounds from ursina.vec3 import Vec3 min_x = self.width min_y = self.height min_z = self.depth max_x = 0 max_y = 0 max_z = 0 for (x, y, z), value in enumerate_3d(self): if value: min_x = min(min_x, x) min_y = min(min_y, y) min_z = min(min_z, z) max_x = max(max_x, x) max_y = max(max_y, y) max_z = max(max_z, z) return Bounds(start=Vec3(min_x, min_y, min_z), end=Vec3(max_x, max_y, max_z)) ``` -------------------------------- ### Button Initialization and Properties Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to create a Button instance and set its various properties like text, color, scale, and origin. ```APIDOC ## Button Initialization ### Description Creates a button with customizable text, appearance, and behavior. ### Parameters - **text** (str) - Optional - The text to display on the button. - **parent** (Entity) - Optional - The parent entity for the button. - **model** (str) - Optional - The model to use for the button's visual representation. - **radius** (float) - Optional - The corner radius of the button. - **origin** (tuple) - Optional - The origin point of the button. - **text_origin** (tuple) - Optional - The origin point for the button's text. - **text_size** (float) - Optional - The size of the button's text. - **color** (Color) - Optional - The color of the button. - **collider** (str) - Optional - The type of collider for the button. - **highlight_scale** (float) - Optional - The scale multiplier when the mouse hovers over the button. - **pressed_scale** (float) - Optional - The scale multiplier when the button is pressed. - **disabled** (bool) - Optional - Whether the button is disabled. ### Properties - **.text** (str) - The text displayed on the button. - **.text_origin** (tuple) - The origin of the button's text. - **.text_color** (Color) - The color of the button's text. - **.icon** (str) - Path to an icon to display on the button. - **.icon_world_scale** (float) - The world scale of the icon. - **.text_size** (float) - The size of the button's text. - **.origin** (tuple) - The origin of the button. - **.color** (Color) - The color of the button. - **.highlight_color** (Color) - The color when the mouse hovers over the button. - **.pressed_color** (Color) - The color when the button is pressed. - **.highlight_scale** (float) - The scale multiplier for highlighting. - **.pressed_scale** (float) - The scale multiplier for pressing. - **.highlight_sound** (Audio) - Sound played when the mouse enters the button. - **.pressed_sound** (Audio) - Sound played when the button is pressed. - **.collider** (str) - The collider type. - **.disabled** (bool) - Whether the button is disabled. - **.text_entity** (Text) - The text entity associated with the button. ### Methods - **input(key)**: Handles keyboard input. - **on_mouse_enter()**: Called when the mouse enters the button's area. - **on_mouse_exit()**: Called when the mouse exits the button's area. - **fit_to_text(radius=.1, padding=Vec2(Text.size*1.5, Text.size))**: Adjusts the button's size to fit its text. ``` -------------------------------- ### Get Bounds of Array2D Source: https://www.ursinaengine.org/api_reference_v8_2_0/array_tools.html Calculates the bounding box of non-default values in an Array2D. Returns a Bounds object with start and end Vec3 points. ```python @property def bounds(self): from ursina.ursinamath import Bounds from ursina.vec3 import Vec3 min_x = self.width min_y = self.height max_x = 0 max_y = 0 for (x, y), value in enumerate_2d(self): if value: min_x = min(min_x, x) min_y = min(min_y, y) max_x = max(max_x, x) max_y = max(max_y, y) return Bounds(start=Vec3(min_x, min_y, 1), end=Vec3(max_x, max_y, 1)) ``` -------------------------------- ### Get Terrain Height Source: https://www.ursinaengine.org/api_reference_v8_2_0/terraincast.html This example demonstrates how to use terraincast to get the height of the terrain at the player's current position and update the player's y-coordinate accordingly. It requires setting up a terrain entity and a player entity, and then continuously checking the terrain height in the update function. ```python app = Ursina() terrain_entity = Entity(model=Terrain('heightmap_1', skip=8), scale=(40, 5, 20), texture='heightmap_1') player = Entity(model='sphere', color=color.azure, scale=.2, origin_y=-.5) hv = terrain_entity.model.height_values def update(): direction = Vec3(held_keys['d'] - held_keys['a'], 0, held_keys['w'] - held_keys['s']).normalized() player.position += direction * time.dt * 4 y = terraincast(player.world_position, terrain_entity, hv) if y is not None: player.y = y EditorCamera() Sky() app.run() ``` -------------------------------- ### CubicBezier Curve Rendering and Animation Source: https://www.ursinaengine.org/api_reference.html Renders various cubic Bezier curves and demonstrates their use in entity animations. This example requires Ursina to be installed and run. ```python '''Draws a sheet with every curve and its name''' from ursina import * from ursina import Ursina, camera, window, curve, Entity, Mesh, Text, color app = Ursina() camera.orthographic = True camera.fov = 16 camera.position = (9, 6) window.color = color.black def render_curve(curve_function, name): curve_renderer = Entity(model=Mesh(vertices=[Vec3(i / 31, curve_function(i / 31), 0) for i in range(32)], mode='line', thickness=2), color=color.light_gray) label = Text(parent=curve_renderer, text=name, scale=8, color=color.gray, y=-.1) return curve_renderer c = **CubicBezier**(0, .5, 1, .5) print('-----------', c.calculate(.23)) window.exit_button.visible = False window.fps_counter.enabled = False custom_curve = combine(linear, reverse(in_expo), .25) render_curve(custom_curve, 'custom_curve') EditorCamera() app.run() ''' These are used by Entity when animating, like this: e = Entity() e.animate_y(1, curve=curve.in_expo) e2 = Entity(x=1.5) e2.animate_y(1, curve=curve.**CubicBezier**(0,.7,1,.3)) ''' ``` -------------------------------- ### Basic DirectionalLight Example with Shadows Source: https://www.ursinaengine.org/api_reference_v8_2_0/directional_light.html Demonstrates setting up a scene with a DirectionalLight, applying a lit shader to entities, and configuring shadow bounds. Ensure entities use a shader that supports shadows (e.g., lit_with_shadows_shader). ```python from ursina import * from ursina.shaders import lit_with_shadows_shader # you have to apply this shader to enties for them to receive shadows. app = Ursina() Entity.default_shader = lit_with_shadows_shader ground = Entity(model='plane', scale=10, texture='grass') lit_cube = Entity(model='cube', y=1, color=color.light_gray) light = DirectionalLight() light.look_at(Vec3(1,-1,1)) shadow_bounds_box = Entity(model='wireframe_cube', scale=5, visible=0) light.update_bounds(shadow_bounds_box) EditorCamera(rotation=(30,30,0)) Sky() app.run() ``` -------------------------------- ### Scene Management and Entity Interaction Source: https://www.ursinaengine.org/api_reference.html Demonstrates basic scene setup, entity creation, editor camera usage, skybox, and custom input handling for listing entity names and clearing the scene. It also shows how to set exponential and linear fog density. ```python from ursina import * app = Ursina() e = Entity(model='plane', color=color.black, scale=100) EditorCamera() s = Sky() def input(key): if key == 'l': for e in scene.entities: print(e.name) if key == 'd': scene.clear() Entity(model='cube') scene.fog_density = .1 # sets exponential density scene.fog_density = (50, 200) # sets linear density start and end app.run() ``` -------------------------------- ### Create a Cylinder Mesh Source: https://www.ursinaengine.org/api_reference.html Generates a Cylinder mesh with specified resolution, radius, and height. The example demonstrates setting the start position and includes an editor camera. ```python app = Ursina() Entity(model=Cylinder(6, start=-.5), color=color.hsv(60,1,1,.3)) origin = Entity(model='quad', color=color.orange, scale=(5, .05)) ed = EditorCamera(rotation_speed = 200, panning_speed=200) app.run() ``` -------------------------------- ### Initialize Tilemap and Set Camera Source: https://www.ursinaengine.org/api_reference.html Demonstrates how to initialize a Tilemap with a custom tileset and size, set its canvas texture, and configure the camera for an orthographic view centered on the tilemap. ```python app = Ursina() EditorCamera() tilemap = Tilemap('tilemap_test_level', tileset='test_tileset', tileset_size=(8,4), parent=scene) tilemap.canvas.texture = 'tilemap_test_level' camera.orthographic = True camera.position = tilemap.tilemap.size / 2 camera.fov = tilemap.tilemap.height Text('press tab to toggle edit mode', origin=(.5,0), position=(-.55,.4)) app.run() ``` -------------------------------- ### Ursina Sequence Example Source: https://www.ursinaengine.org/api_reference.html Demonstrates the creation and control of a Sequence object, which allows chaining functions, delays, and other actions over time. Sequences can be started, paused, resumed, and finished. ```python from ursina import * from ursina import Ursina, Entity app = Ursina() e = Entity(model='quad') def some_func(): print('some_func') s = Sequence(some_func, 1, Func(print, 'one'), Func(e.fade_out, duration=1), Wait(1), loop=True) for i in range(8): s.append(Func(print, i)) s.append(Wait(.2)) print(s) def input(key): actions = {'s' : s.start, 'f' : s.finish, 'p' : s.pause, 'r' : s.resume} if key in actions: actions[key]() app.run() ```