Input and audio
Input
All input for the frame is in one place: the InputSystem resource. Keys and mouse buttons are an array of AppButtons, each with is_pressed, pressed_this_frame and released_this_frame.
InputSystem *input = ecs_resource_get_mut(world, InputSystem);
// once a frame, on the main lane
input_update(input, &memory->input_events, memory->total_time);
if (input->buttons[KEY_SPACE].pressed_this_frame) jump = true;
v2 look = input->mouse_delta;
InputGamepad *pad = &input->gamepads[input->active_gamepad];
v2 move = input_gamepad_stick(pad->left_stick, 0.15f); // 0.15: the dead zoneTouches are in input->touches, up to four fingers with their start and current positions. For a phone game, the touch_controls gameplay block draws a stick and buttons for you.
A good pattern, and the one the template uses: read input on the main lane into a small controls resource ("move this way, jump"), and let your systems read that. The systems don't care if it came from a keyboard, a gamepad or a finger, and you can drive them from a script or the network.
os_lock_mouse(true) captures the mouse for mouse look.
Recording a session
hz/hzbuild run -- --record bug.hzrec saves every frame's input, and -- --replay bug.hzrec plays it back. Great for bugs that are hard to reproduce by hand.
Audio
Kaigen has its own mixer. Sounds play on buses (AUDIO_BUS_SFX, _MUSIC, _UI, _VOICE) that you can turn up, down or add effects to, and voices can be positioned in 3D.
ecs_audio_play(world, "my_game/sounds/coin.wav",
&(EcsAudioPlayDesc){.volume = 0.8f, .bus = AUDIO_BUS_SFX});
ecs_audio_play_at(world, "my_game/sounds/explosion.wav", position, NULL);For sounds that belong to something in the world (a fire crackling, a radio), put an AudioSourceComp on the entity. You can set it up in the editor, and the sound follows the entity. The entity with AudioListenerComp (usually the camera) is where you hear from.
Sounds are cooked to QOA, which is small and very cheap to decode. Long music can stream from disk (audio_source_from_qoa_file) instead of sitting in memory.
Worth knowing
- A sound plays once its asset has loaded, so the first play of a sound can come a few frames late. Load the sounds you need right away when the level starts.
- On the web, browsers only allow audio after the player clicks or presses a key. That's the browser, not your game.
Input is hz/src/engine/input.h; audio is hz/src/engine/audio.h and hz/src/engine/ecs/audio/ecs_audio.h.