Turbo Documentation

website·Indexed 33 days ago

https://docs.turbo.computer/

Documentation for Turbo, a game development framework using Rust. It provides APIs for 2D graphics (sprites, shapes, nine-slice scaling), audio, input handling (keyboard, mouse, gamepad, pointer), networking, and a dedicated CLI for project management.

Tokens
30.7K
Snippets
192
Records
212
Agent score
59%

What's inside Turbo

  1. Overview of the Camera coordinate system

    The camera module shifts the window's viewport of the game's canvas. By default, the camera position is centered in the viewport in pixels: the x position starts at half the width and the y position starts at half the height of the game's resolution. The z position (zoom) defaults to 1.0.
  2. Overview of the Turbo Game Engine

    Turbo is a command-line based game engine powered by WebAssembly and WebGPU. It is specifically designed for creating low-resolution 2D games using a quad-based render pipeline and does not support 3D features. To develop with Turbo, users must be comfortable using a command-line interface (via the turbo executable) for project initialization, execution, and exporting. The officially supported SDK is written in Rust.
  3. Overview of Turbo OS Channels

    The channel API allows a game to subscribe to a Turbo OS channel to send and receive incoming messages asynchronously. It is designed for low-latency requirements and group broadcasts, making it suitable for fast-paced multiplayer gameplay and chat systems.
  4. Animate values using the Tween struct

    Tween is a generic struct used to handle smooth transitions between values over time. It allows developers to define a starting value, a target value, a duration (in ticks/frames), and an easing function to control the acceleration of the transition.
  5. Implement resizable UI elements using Nine-Slice scaling

    Nine-slice scaling (also known as Scale 9 grid or 9-patch) is a 2D image resizing technique that splits an image into a grid of nine parts. This allows UI elements, such as buttons and text boxes, to be resized while keeping the borders proportionally intact and undistorted.
  6. Manage game time using Turbo Time APIs

    Turbo provides two distinct ways to track time depending on the requirement:

    1. Monotonic/Deterministic Time: Use time::tick() for game logic, measuring elapsed frames, or scheduling gameplay events. This is unaffected by system clock changes or time zones.
    2. Real-world Time: Use time::now() for Unix timestamps, displaying current time, or comparing against external timestamps.
  7. Publish a Turbo game to the web

    After running turbo export, upload the contents of the generated www directory to a web hosting service.

    Recommended free hosting options include:

    • Netlify: Supports drag-and-drop upload of the www directory via Netlify Drop.
    • Itch.io: Create a new project, set the 'Kind of project' to HTML, and upload a zipped version of the www directory.
  8. Create a Turbo OS Channel on the Server

    To create a server-side channel, define the message types for sending and receiving, use the #[turbo::os::channel] macro to register the program and channel name, and implement the ChannelHandler trait. The on_data method handles incoming messages from clients, and Self::send is used to respond to specific users.
    use turbo::*;
    
    #[turbo::serialize]
    pub struct Ping;
    
    #[turbo::serialize]
    pub struct Pong;
    
    #[turbo::os::channel(program = "pingpong", name = "main")]
    pub struct PingPongChannel;
    
    impl ChannelHandler for PingPongChannel {
        type Recv = Ping; // Incoming from client
        type Send = Pong; // Outgoing to client
    
        fn new() -> Self {
            Self
        }
    
        fn on_data(&mut self, user_id: &str, data: Self::Recv) -> Result<(), std::io::Error> {
            log!("Got {:?} from {:?}", data, user_id);
            Self::send(user_id, Pong)
        }
    }
  9. Implement a Game State Machine for scene management

    Use an enum to manage different game screens (e.g., Menu and Game). By tracking the current screen in the GameState struct, you can conditionally execute update logic and rendering based on whether the player is in the menu, active gameplay, or a game-over state.
    #[turbo::serialize]
    #[derive(PartialEq)]
    enum Screen {
        Menu,
        Game,
    }
    
    #[turbo::game]
    struct GameState {
        screen: Screen,
        start_tick: usize,
        player: Player,
        enemies: Vec<Enemy>,
        projectiles: Vec<Projectile>,
    }
    
    impl GameState {
        fn new() -> Self {
            Self {
                screen: Screen::Menu,
                start_tick: 0,
                player: Player::new(),
                enemies: vec![],
                projectiles: vec![],
            }
        }
    
        fn update(&mut self) {
            self.draw();
            if self.screen == Screen::Menu {
                // Transition to game on input
                if gamepad::get(0).start.just_pressed() || gamepad::get(0).a.just_pressed() {
                    self.screen = Screen::Game;
                    self.start_tick = time::tick();
                }
            } else {
                // Game logic
                self.player.update(&mut self.projectiles);
                self.spawn_enemies();
                // ... enemy and projectile updates ...
    
                // Game Over logic
                if self.player.hp == 0 {
                    if gamepad::get(0).start.just_pressed() || gamepad::get(0).a.just_pressed() {
                        *self = GameState::new(); // Reset game
                    }
                }
            }
        }
    }
  10. Set up and use sprites in Turbo

    To use sprites in a Turbo project, create a folder named sprites in your project's root directory. This folder serves as the asset directory for all game sprites. You can organize assets using subfolders within the sprites directory and reference them using the path relative to the root (e.g., my-folder-name/my-file-name).
    your-project-dir/
    ├── sprites/            # The directory of your sprite assets
    ├── src/
    │   └── lib.rs
    ├── Cargo.toml
    └── turbo.toml