0Pricing
Learn Rust Coding · Урок

Создание и перемещение сущностей

Размещайте объекты на экране.

«Создание и перемещение сущностей» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Commands: Deferred Spawning

You can't mutate the World directly while systems run in parallel. Instead, you queue structural changes through Commands.

Spawning, despawning, and adding components are recorded and applied at the end of the schedule stage, keeping access safe.

fn setup(mut commands: Commands) {
    commands.spawn_empty();
}

Spawning with a Bundle

A bundle is a group of components inserted together. The simplest bundle is just a tuple of components.

Bevy treats each tuple element as a component to attach, so one spawn call can give an entity all its starting data.

fn setup(mut commands: Commands) {
    commands.spawn((
        Position { x: 0.0, y: 0.0 },
        Velocity { x: 1.5, y: 0.0 },
        Player,
    ));
}

A Camera to See

Nothing renders without a camera. For 2D games you spawn a Camera2d in your startup system.

The camera is itself an entity with camera components — another example of ECS uniformity. Everything in the scene is an entity.

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d::default());
}

Spawning a Sprite

To draw something, give an entity a Sprite plus a Transform. The transform holds position, rotation, and scale in world space.

A colored sprite needs no image asset, which is handy for prototyping movement before importing art.

commands.spawn((
    Sprite::from_color(Color::srgb(0.2, 0.7, 1.0), Vec2::new(40.0, 40.0)),
    Transform::from_xyz(0.0, 0.0, 0.0),
    Velocity { x: 80.0, y: 0.0 },
));

Transform vs Custom Position

In real Bevy games you usually move the built-in Transform rather than a custom Position, because rendering reads Transform directly.

The translation is a Vec3. For 2D you change x and y and keep z for draw ordering.

#[derive(Component)]
struct Velocity { x: f32, y: f32 }

fn apply_velocity(mut q: Query<(&mut Transform, &Velocity)>) {
    for (mut tf, vel) in &mut q {
        tf.translation.x += vel.x;
        tf.translation.y += vel.y;
    }
}

Iterating a Query Mutably

To change component data you request &mut T and iterate over &mut query. Each item yields mutable references.

Bevy guarantees no two systems hold conflicting mutable access at once, so this loop is safe even while other systems run.

fn move_all(mut q: Query<&mut Transform, With<Player>>) {
    for mut tf in &mut q {
        tf.translation.x += 1.0;
    }
}

Spawning Many Entities

Loops let you populate a level. Call spawn inside a Rust for loop to create a grid of obstacles or a swarm of enemies.

Each iteration queues its own command, and all of them are applied together at the stage boundary.

fn spawn_row(mut commands: Commands) {
    for i in 0..5 {
        commands.spawn((
            Sprite::from_color(Color::WHITE, Vec2::splat(20.0)),
            Transform::from_xyz(i as f32 * 30.0, 0.0, 0.0),
        ));
    }
}

Despawning Entities

Remove an entity entirely with commands.entity(id).despawn(). This frees its components and recycles the entity index.

You typically despawn from a system that queried the entity's Entity id, for example a bullet that left the screen.

fn cleanup(mut commands: Commands, q: Query<(Entity, &Transform)>) {
    for (e, tf) in &q {
        if tf.translation.y > 600.0 {
            commands.entity(e).despawn();
        }
    }
}

Adding Components Later

You can attach new components to an existing entity at runtime via insert. This is how you give a powered-up player a Shield tag.

Removing works the same way with remove::<T>(). Both are structural changes, so they go through Commands.

commands.entity(player).insert(Shield { hits: 3 });
// later
commands.entity(player).remove::<Shield>();

Z for Layering

In 2D, the z value of a transform's translation decides draw order. Higher z renders on top.

Give the background a low z and the player a higher one so sprites never disappear behind the scenery.

// background behind, player in front
commands.spawn((bg_sprite, Transform::from_xyz(0.0, 0.0, 0.0)));
commands.spawn((player_sprite, Transform::from_xyz(0.0, 0.0, 10.0)));

Wiring It Up

Spawn in Startup, move in Update. The startup system creates the camera and entities once; the update system advances them every frame.

This separation keeps initialization out of your per-frame hot path.

App::new()
    .add_plugins(DefaultPlugins)
    .add_systems(Startup, setup)
    .add_systems(Update, apply_velocity)
    .run();

Quick Check

Think about how structural changes are applied.

Recap: Spawning and Moving

You spawn entities with bundles via Commands, render them with Sprite and Transform, and move them by mutating the transform in an Update system.

Despawn and component insertion are also commands. Next we'll make movement react to keyboard input and real elapsed time.

Часто задаваемые вопросы

Урок «Создание и перемещение сущностей» бесплатный?

Да — полный текст урока «Создание и перемещение сущностей» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.

Чему я научусь в уроке «Создание и перемещение сущностей»?

Размещайте объекты на экране. Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Learn Rust Coding?

Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Создание и перемещение сущностей»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Learn Rust Coding?

Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Мышление в стиле ECS
  2. Создание и перемещение сущностей
  3. Обработка ввода и времени
  4. Столкновения и состояние игры
← Назад к Learn Rust Coding