0Pricing
Learn Rust Coding · 강의

입력과 시간 처리하기

플레이어와 시계에 반응해 보세요.

입력과 시간 처리하기은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Input as a Resource

Keyboard state lives in the ButtonInput<KeyCode> resource, provided by DefaultPlugins.

Request it read-only with Res. Bevy updates it each frame before your systems run, so you always see the current state.

fn read_keys(keys: Res<ButtonInput<KeyCode>>) {
    if keys.pressed(KeyCode::Space) {
        info!("space held");
    }
}

pressed vs just_pressed

pressed is true every frame a key is held — ideal for continuous movement. just_pressed is true only on the frame the key goes down.

Use just_pressed for discrete actions like jumping or firing so a single tap fires once.

fn jump(keys: Res<ButtonInput<KeyCode>>) {
    if keys.just_pressed(KeyCode::ArrowUp) {
        info!("jump!");
    }
}

Building a Direction Vector

Combine multiple keys into a movement direction. Start at zero and add a unit on each axis for each pressed key.

Normalizing the result prevents diagonal movement from being faster than straight movement.

fn direction(keys: Res<ButtonInput<KeyCode>>) -> Vec2 {
    let mut d = Vec2::ZERO;
    if keys.pressed(KeyCode::KeyW) { d.y += 1.0; }
    if keys.pressed(KeyCode::KeyS) { d.y -= 1.0; }
    if keys.pressed(KeyCode::KeyA) { d.x -= 1.0; }
    if keys.pressed(KeyCode::KeyD) { d.x += 1.0; }
    d.normalize_or_zero()
}

The Time Resource

Frame rates vary by machine, so never move by a fixed amount per frame. The Time resource gives you delta_secs(), the seconds since the last frame.

Multiplying speed by delta makes movement frame-rate independent.

fn move_player(time: Res<Time>, mut q: Query<&mut Transform, With<Player>>) {
    let dt = time.delta_secs();
    for mut tf in &mut q {
        tf.translation.x += 200.0 * dt;
    }
}

Combining Input and Time

The real pattern joins both resources in one system: read the direction from input, then scale it by speed and delta.

This produces smooth, consistent control regardless of whether the game runs at 30 or 144 frames per second.

fn drive(
    keys: Res<ButtonInput<KeyCode>>,
    time: Res<Time>,
    mut q: Query<&mut Transform, With<Player>>,
) {
    let mut d = Vec2::ZERO;
    if keys.pressed(KeyCode::KeyA) { d.x -= 1.0; }
    if keys.pressed(KeyCode::KeyD) { d.x += 1.0; }
    let step = d.normalize_or_zero() * 300.0 * time.delta_secs();
    for mut tf in &mut q {
        tf.translation += step.extend(0.0);
    }
}

Mouse Buttons

Mouse buttons use the same ButtonInput API with MouseButton instead of KeyCode.

This consistency means the pressed and just_pressed habits you built for the keyboard transfer directly to clicks.

fn shoot(buttons: Res<ButtonInput<MouseButton>>) {
    if buttons.just_pressed(MouseButton::Left) {
        info!("fire");
    }
}

Timers for Cooldowns

A Timer tracks elapsed time toward a target duration. Tick it with the frame delta each update.

Use a repeating timer for a firing cadence and check just_finished() to know when to act.

#[derive(Component)]
struct Cooldown(Timer);

fn tick(time: Res<Time>, mut q: Query<&mut Cooldown>) {
    for mut cd in &mut q {
        cd.0.tick(time.delta());
        if cd.0.just_finished() { info!("ready"); }
    }
}

Creating a Timer

Construct a timer from a duration and a TimerMode. Once stops after firing; Repeating resets automatically.

Store it on a component so each entity, such as a turret, can have its own independent cadence.

use std::time::Duration;

commands.spawn((
    Turret,
    Cooldown(Timer::new(Duration::from_millis(500), TimerMode::Repeating)),
));

FixedUpdate for Determinism

Physics and netcode often need a fixed timestep. Systems in the FixedUpdate schedule run a constant number of times per second, regardless of render rate.

Inside them, use Time<Fixed> whose delta is always the same, giving reproducible simulation.

App::new()
    .add_plugins(DefaultPlugins)
    .add_systems(FixedUpdate, physics_step)
    .run();

Elapsed vs Delta

time.delta_secs() is the gap since last frame. time.elapsed_secs() is the total time since startup.

Elapsed is great for animations driven by a sine wave, like a bobbing pickup, where you feed total time into the function.

fn bob(time: Res<Time>, mut q: Query<&mut Transform, With<Pickup>>) {
    let t = time.elapsed_secs();
    for mut tf in &mut q {
        tf.translation.y = (t * 2.0).sin() * 10.0;
    }
}

Clamping to Bounds

After moving, keep the player on screen by clamping the transform within the window's half-extents.

f32::clamp bounds each axis. Read the window size from the Window query when you need exact limits.

fn clamp(mut q: Query<&mut Transform, With<Player>>) {
    for mut tf in &mut q {
        tf.translation.x = tf.translation.x.clamp(-300.0, 300.0);
        tf.translation.y = tf.translation.y.clamp(-200.0, 200.0);
    }
}

Quick Check

Consider frame-rate independence.

Recap: Input and Time

Input lives in ButtonInput resources; use pressed for held actions and just_pressed for taps. The Time resource and Timer components keep movement and cooldowns frame-rate independent.

With control in place, the final lesson adds collisions and game state transitions.

자주 묻는 질문

“입력과 시간 처리하기” 강의는 무료인가요?

네 — “입력과 시간 처리하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“입력과 시간 처리하기”에서 뭘 배우나요?

플레이어와 시계에 반응해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“입력과 시간 처리하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. ECS 사고방식
  2. 엔터티 생성하고 이동하기
  3. 입력과 시간 처리하기
  4. 충돌과 게임 상태
← Learn Rust Coding(으)로 돌아가기