Skip to content

Commit ac63c49

Browse files
committedJan 25, 2022
Simple 2d rotation example (#3065)
# Objective Some new bevy users are unfamiliar with quaternions and have trouble working with rotations in 2D. There has been an [issue](bitshifter/glam-rs#226) raised with glam to add helpers to better support these users, however for now I feel could be better to provide examples of how to do this in Bevy as a starting point for new users. ## Solution I've added a 2d_rotation example which demonstrates 3 different rotation examples to try help get people started: - Rotating and translating a player ship based on keyboard input - An enemy ship type that rotates to face the player ship immediately - An enemy ship type that rotates to face the player at a fixed angular velocity I also have a standalone version of this example here https://github.com/bitshifter/bevy-2d-rotation-example but I think it would be more discoverable if it's included with Bevy.
1 parent 6d76229 commit ac63c49

File tree

8 files changed

+279
-0
lines changed

8 files changed

+279
-0
lines changed
 

‎CREDITS.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@
2020
* Cake from [Kenney's Food Kit](https://www.kenney.nl/assets/food-kit) (CC0 1.0 Universal)
2121
* Ground tile from [Kenney's Tower Defense Kit](https://www.kenney.nl/assets/tower-defense-kit) (CC0 1.0 Universal)
2222
* Game icons from [Kenney's Game Icons](https://www.kenney.nl/assets/game-icons) (CC0 1.0 Universal)
23+
* Space ships from [Kenny's Simple Space Kit](https://www.kenney.nl/assets/simple-space) (CC0 1.0 Universal)

‎Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ path = "examples/2d/contributors.rs"
119119
name = "many_sprites"
120120
path = "examples/2d/many_sprites.rs"
121121

122+
[[example]]
123+
name = "2d_rotation"
124+
path = "examples/2d/rotation.rs"
125+
122126
[[example]]
123127
name = "mesh2d"
124128
path = "examples/2d/mesh2d.rs"

‎assets/textures/simplespace/License.txt

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
3+
Simple Space
4+
5+
Created/distributed by Kenney (www.kenney.nl)
6+
Creation date: 03-03-2021
7+
8+
------------------------------
9+
10+
License: (Creative Commons Zero, CC0)
11+
http://creativecommons.org/publicdomain/zero/1.0/
12+
13+
This content is free to use in personal, educational and commercial projects.
14+
Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
15+
16+
------------------------------
17+
18+
Donate: http://support.kenney.nl
19+
Patreon: http://patreon.com/kenney/
20+
21+
Follow on Twitter for updates:
22+
http://twitter.com/KenneyNL
1.12 KB
Loading
1.07 KB
Loading
615 Bytes
Loading

‎examples/2d/rotation.rs

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

‎examples/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ Example | File | Description
9292
`text2d` | [`2d/text2d.rs`](./2d/text2d.rs) | Generates text in 2d
9393
`sprite_flipping` | [`2d/sprite_flipping.rs`](./2d/sprite_flipping.rs) | Renders a sprite flipped along an axis
9494
`texture_atlas` | [`2d/texture_atlas.rs`](./2d/texture_atlas.rs) | Generates a texture atlas (sprite sheet) from individual sprites
95+
`rotation` | [`2d/rotation.rs`](./2d/rotation.rs) | Demonstrates rotating entities in 2D with quaternions
9596

9697
## 3D Rendering
9798

0 commit comments

Comments
 (0)
Please sign in to comment.