rotation/rotation.rs
1//! Demonstrates rotating entities in 2D using quaternions.
2
3use bevy::{math::ops, prelude::*};
4
5const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0);
6
7fn main() {
8 App::new()
9 .add_plugins(DefaultPlugins)
10 .insert_resource(Time::<Fixed>::from_hz(60.0))
11 .add_systems(Startup, setup)
12 .add_systems(
13 FixedUpdate,
14 (
15 player_movement_system,
16 snap_to_player_system,
17 rotate_to_player_system,
18 ),
19 )
20 .run();
21}
22
23/// Player component
24#[derive(Component)]
25struct Player {
26 /// Linear speed in meters per second
27 movement_speed: f32,
28 /// Rotation speed in radians per second
29 rotation_speed: f32,
30}
31
32/// Snap to player ship behavior
33#[derive(Component)]
34struct SnapToPlayer;
35
36/// Rotate to face player ship behavior
37#[derive(Component)]
38struct RotateToPlayer {
39 /// Rotation speed in radians per second
40 rotation_speed: f32,
41}
42
43/// Add the game's entities to our world and creates an orthographic camera for 2D rendering.
44///
45/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
46///
47/// * `X` axis goes from left to right (`+X` points right)
48/// * `Y` axis goes from bottom to top (`+Y` point up)
49/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
50///
51/// The origin is at the center of the screen.
52fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
53 let ship_handle = asset_server.load("textures/simplespace/ship_C.png");
54 let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png");
55 let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png");
56
57 commands.spawn(Camera2d);
58
59 // Create a minimal UI explaining how to interact with the example
60 commands.spawn((
61 Text::new("Up Arrow: Move Forward\nLeft / Right Arrow: Turn"),
62 Node {
63 position_type: PositionType::Absolute,
64 top: Val::Px(12.0),
65 left: Val::Px(12.0),
66 ..default()
67 },
68 ));
69
70 let horizontal_margin = BOUNDS.x / 4.0;
71 let vertical_margin = BOUNDS.y / 4.0;
72
73 // Player controlled ship
74 commands.spawn((
75 Sprite::from_image(ship_handle),
76 Player {
77 movement_speed: 500.0, // Meters per second
78 rotation_speed: f32::to_radians(360.0), // Degrees per second
79 },
80 ));
81
82 // Enemy that snaps to face the player spawns on the bottom and left
83 commands.spawn((
84 Sprite::from_image(enemy_a_handle.clone()),
85 Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0),
86 SnapToPlayer,
87 ));
88 commands.spawn((
89 Sprite::from_image(enemy_a_handle),
90 Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0),
91 SnapToPlayer,
92 ));
93
94 // Enemy that rotates to face the player enemy spawns on the top and right
95 commands.spawn((
96 Sprite::from_image(enemy_b_handle.clone()),
97 Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0),
98 RotateToPlayer {
99 rotation_speed: f32::to_radians(45.0), // Degrees per second
100 },
101 ));
102 commands.spawn((
103 Sprite::from_image(enemy_b_handle),
104 Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0),
105 RotateToPlayer {
106 rotation_speed: f32::to_radians(90.0), // Degrees per second
107 },
108 ));
109}
110
111/// Demonstrates applying rotation and movement based on keyboard input.
112fn player_movement_system(
113 time: Res<Time>,
114 keyboard_input: Res<ButtonInput<KeyCode>>,
115 query: Single<(&Player, &mut Transform)>,
116) {
117 let (ship, mut transform) = query.into_inner();
118
119 let mut rotation_factor = 0.0;
120 let mut movement_factor = 0.0;
121
122 if keyboard_input.pressed(KeyCode::ArrowLeft) {
123 rotation_factor += 1.0;
124 }
125
126 if keyboard_input.pressed(KeyCode::ArrowRight) {
127 rotation_factor -= 1.0;
128 }
129
130 if keyboard_input.pressed(KeyCode::ArrowUp) {
131 movement_factor += 1.0;
132 }
133
134 // Update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen)
135 transform.rotate_z(rotation_factor * ship.rotation_speed * time.delta_secs());
136
137 // Get the ship's forward vector by applying the current rotation to the ships initial facing
138 // vector
139 let movement_direction = transform.rotation * Vec3::Y;
140 // Get the distance the ship will move based on direction, the ship's movement speed and delta
141 // time
142 let movement_distance = movement_factor * ship.movement_speed * time.delta_secs();
143 // Create the change in translation using the new movement direction and distance
144 let translation_delta = movement_direction * movement_distance;
145 // Update the ship translation with our new translation delta
146 transform.translation += translation_delta;
147
148 // Bound the ship within the invisible level bounds
149 let extents = Vec3::from((BOUNDS / 2.0, 0.0));
150 transform.translation = transform.translation.min(extents).max(-extents);
151}
152
153/// Demonstrates snapping the enemy ship to face the player ship immediately.
154fn snap_to_player_system(
155 mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,
156 player_transform: Single<&Transform, With<Player>>,
157) {
158 // Get the player translation in 2D
159 let player_translation = player_transform.translation.xy();
160
161 for mut enemy_transform in &mut query {
162 // Get the vector from the enemy ship to the player ship in 2D and normalize it.
163 let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
164
165 // Get the quaternion to rotate from the initial enemy facing direction to the direction
166 // facing the player
167 let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));
168
169 // Rotate the enemy to face the player
170 enemy_transform.rotation = rotate_to_player;
171 }
172}
173
174/// Demonstrates rotating an enemy ship to face the player ship at a given rotation speed.
175///
176/// This method uses the vector dot product to determine if the enemy is facing the player and
177/// if not, which way to rotate to face the player. The dot product on two unit length vectors
178/// will return a value between -1.0 and +1.0 which tells us the following about the two vectors:
179///
180/// * If the result is 1.0 the vectors are pointing in the same direction, the angle between them is
181/// 0 degrees.
182/// * If the result is 0.0 the vectors are perpendicular, the angle between them is 90 degrees.
183/// * If the result is -1.0 the vectors are parallel but pointing in opposite directions, the angle
184/// between them is 180 degrees.
185/// * If the result is positive the vectors are pointing in roughly the same direction, the angle
186/// between them is greater than 0 and less than 90 degrees.
187/// * If the result is negative the vectors are pointing in roughly opposite directions, the angle
188/// between them is greater than 90 and less than 180 degrees.
189///
190/// It is possible to get the angle by taking the arc cosine (`acos`) of the dot product. It is
191/// often unnecessary to do this though. Beware than `acos` will return `NaN` if the input is less
192/// than -1.0 or greater than 1.0. This can happen even when working with unit vectors due to
193/// floating point precision loss, so it pays to clamp your dot product value before calling
194/// `acos`.
195fn rotate_to_player_system(
196 time: Res<Time>,
197 mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,
198 player_transform: Single<&Transform, With<Player>>,
199) {
200 // Get the player translation in 2D
201 let player_translation = player_transform.translation.xy();
202
203 for (config, mut enemy_transform) in &mut query {
204 // Get the enemy ship forward vector in 2D (already unit length)
205 let enemy_forward = (enemy_transform.rotation * Vec3::Y).xy();
206
207 // Get the vector from the enemy ship to the player ship in 2D and normalize it.
208 let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
209
210 // Get the dot product between the enemy forward vector and the direction to the player.
211 let forward_dot_player = enemy_forward.dot(to_player);
212
213 // If the dot product is approximately 1.0 then the enemy is already facing the player and
214 // we can early out.
215 if (forward_dot_player - 1.0).abs() < f32::EPSILON {
216 continue;
217 }
218
219 // Get the right vector of the enemy ship in 2D (already unit length)
220 let enemy_right = (enemy_transform.rotation * Vec3::X).xy();
221
222 // Get the dot product of the enemy right vector and the direction to the player ship.
223 // If the dot product is negative them we need to rotate counter clockwise, if it is
224 // positive we need to rotate clockwise. Note that `copysign` will still return 1.0 if the
225 // dot product is 0.0 (because the player is directly behind the enemy, so perpendicular
226 // with the right vector).
227 let right_dot_player = enemy_right.dot(to_player);
228
229 // Determine the sign of rotation from the right dot player. We need to negate the sign
230 // here as the 2D bevy co-ordinate system rotates around +Z, which is pointing out of the
231 // screen. Due to the right hand rule, positive rotation around +Z is counter clockwise and
232 // negative is clockwise.
233 let rotation_sign = -f32::copysign(1.0, right_dot_player);
234
235 // Limit rotation so we don't overshoot the target. We need to convert our dot product to
236 // an angle here so we can get an angle of rotation to clamp against.
237 let max_angle = ops::acos(forward_dot_player.clamp(-1.0, 1.0)); // Clamp acos for safety
238
239 // Calculate angle of rotation with limit
240 let rotation_angle =
241 rotation_sign * (config.rotation_speed * time.delta_secs()).min(max_angle);
242
243 // Rotate the enemy to face the player
244 enemy_transform.rotate_z(rotation_angle);
245 }
246}