3d_rotation/
3d_rotation.rs

1//! Illustrates how to rotate an object around an axis.
2
3use bevy::prelude::*;
4
5use std::f32::consts::TAU;
6
7// Define a component to designate a rotation speed to an entity.
8#[derive(Component)]
9struct Rotatable {
10    speed: f32,
11}
12
13fn main() {
14    App::new()
15        .add_plugins(DefaultPlugins)
16        .add_systems(Startup, setup)
17        .add_systems(Update, rotate_cube)
18        .run();
19}
20
21fn setup(
22    mut commands: Commands,
23    mut meshes: ResMut<Assets<Mesh>>,
24    mut materials: ResMut<Assets<StandardMaterial>>,
25) {
26    // Spawn a cube to rotate.
27    commands.spawn((
28        Mesh3d(meshes.add(Cuboid::default())),
29        MeshMaterial3d(materials.add(Color::WHITE)),
30        Transform::from_translation(Vec3::ZERO),
31        Rotatable { speed: 0.3 },
32    ));
33
34    // Spawn a camera looking at the entities to show what's happening in this example.
35    commands.spawn((
36        Camera3d::default(),
37        Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
38    ));
39
40    // Add a light source so we can see clearly.
41    commands.spawn((
42        DirectionalLight::default(),
43        Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
44    ));
45}
46
47// This system will rotate any entity in the scene with a Rotatable component around its y-axis.
48fn rotate_cube(mut cubes: Query<(&mut Transform, &Rotatable)>, timer: Res<Time>) {
49    for (mut transform, cube) in &mut cubes {
50        // The speed is first multiplied by TAU which is a full rotation (360deg) in radians,
51        // and then multiplied by delta_secs which is the time that passed last frame.
52        // In other words. Speed is equal to the amount of rotations per second.
53        transform.rotate_y(cube.speed * TAU * timer.delta_secs());
54    }
55}