//! Demonstrates rotating entities in 2D using quaternions.12use bevy::{math::ops, prelude::*};34const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0);56fn main() {7App::new()8.add_plugins(DefaultPlugins)9.insert_resource(Time::<Fixed>::from_hz(60.0))10.add_systems(Startup, setup)11.add_systems(12FixedUpdate,13(14player_movement_system,15snap_to_player_system,16rotate_to_player_system,17),18)19.run();20}2122/// Player component23#[derive(Component)]24struct Player {25/// Linear speed in meters per second26movement_speed: f32,27/// Rotation speed in radians per second28rotation_speed: f32,29}3031/// Snap to player ship behavior32#[derive(Component)]33struct SnapToPlayer;3435/// Rotate to face player ship behavior36#[derive(Component)]37struct RotateToPlayer {38/// Rotation speed in radians per second39rotation_speed: f32,40}4142/// Add the game's entities to our world and creates an orthographic camera for 2D rendering.43///44/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:45///46/// * `X` axis goes from left to right (`+X` points right)47/// * `Y` axis goes from bottom to top (`+Y` point up)48/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)49///50/// The origin is at the center of the screen.51fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {52let ship_handle = asset_server.load("textures/simplespace/ship_C.png");53let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png");54let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png");5556commands.spawn(Camera2d);5758// Create a minimal UI explaining how to interact with the example59commands.spawn((60Text::new("Up Arrow: Move Forward\nLeft / Right Arrow: Turn"),61Node {62position_type: PositionType::Absolute,63top: px(12),64left: px(12),65..default()66},67));6869let horizontal_margin = BOUNDS.x / 4.0;70let vertical_margin = BOUNDS.y / 4.0;7172// Player controlled ship73commands.spawn((74Sprite::from_image(ship_handle),75Player {76movement_speed: 500.0, // Meters per second77rotation_speed: f32::to_radians(360.0), // Degrees per second78},79));8081// Enemy that snaps to face the player spawns on the bottom and left82commands.spawn((83Sprite::from_image(enemy_a_handle.clone()),84Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0),85SnapToPlayer,86));87commands.spawn((88Sprite::from_image(enemy_a_handle),89Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0),90SnapToPlayer,91));9293// Enemy that rotates to face the player enemy spawns on the top and right94commands.spawn((95Sprite::from_image(enemy_b_handle.clone()),96Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0),97RotateToPlayer {98rotation_speed: f32::to_radians(45.0), // Degrees per second99},100));101commands.spawn((102Sprite::from_image(enemy_b_handle),103Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0),104RotateToPlayer {105rotation_speed: f32::to_radians(90.0), // Degrees per second106},107));108}109110/// Demonstrates applying rotation and movement based on keyboard input.111fn player_movement_system(112time: Res<Time>,113keyboard_input: Res<ButtonInput<KeyCode>>,114query: Single<(&Player, &mut Transform)>,115) {116let (ship, mut transform) = query.into_inner();117118let mut rotation_factor = 0.0;119let mut movement_factor = 0.0;120121if keyboard_input.pressed(KeyCode::ArrowLeft) {122rotation_factor += 1.0;123}124125if keyboard_input.pressed(KeyCode::ArrowRight) {126rotation_factor -= 1.0;127}128129if keyboard_input.pressed(KeyCode::ArrowUp) {130movement_factor += 1.0;131}132133// Update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen)134transform.rotate_z(rotation_factor * ship.rotation_speed * time.delta_secs());135136// Get the ship's forward vector by applying the current rotation to the ships initial facing137// vector138let movement_direction = transform.rotation * Vec3::Y;139// Get the distance the ship will move based on direction, the ship's movement speed and delta140// time141let movement_distance = movement_factor * ship.movement_speed * time.delta_secs();142// Create the change in translation using the new movement direction and distance143let translation_delta = movement_direction * movement_distance;144// Update the ship translation with our new translation delta145transform.translation += translation_delta;146147// Bound the ship within the invisible level bounds148let extents = Vec3::from((BOUNDS / 2.0, 0.0));149transform.translation = transform.translation.min(extents).max(-extents);150}151152/// Demonstrates snapping the enemy ship to face the player ship immediately.153fn snap_to_player_system(154mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,155player_transform: Single<&Transform, With<Player>>,156) {157// Get the player translation in 2D158let player_translation = player_transform.translation.xy();159160for mut enemy_transform in &mut query {161// Get the vector from the enemy ship to the player ship in 2D and normalize it.162let to_player = (player_translation - enemy_transform.translation.xy()).normalize();163164// Get the quaternion to rotate from the initial enemy facing direction to the direction165// facing the player166let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));167168// Rotate the enemy to face the player169enemy_transform.rotation = rotate_to_player;170}171}172173/// Demonstrates rotating an enemy ship to face the player ship at a given rotation speed.174///175/// This method uses the vector dot product to determine if the enemy is facing the player and176/// if not, which way to rotate to face the player. The dot product on two unit length vectors177/// will return a value between -1.0 and +1.0 which tells us the following about the two vectors:178///179/// * If the result is 1.0 the vectors are pointing in the same direction, the angle between them is180/// 0 degrees.181/// * If the result is 0.0 the vectors are perpendicular, the angle between them is 90 degrees.182/// * If the result is -1.0 the vectors are parallel but pointing in opposite directions, the angle183/// between them is 180 degrees.184/// * If the result is positive the vectors are pointing in roughly the same direction, the angle185/// between them is greater than 0 and less than 90 degrees.186/// * If the result is negative the vectors are pointing in roughly opposite directions, the angle187/// between them is greater than 90 and less than 180 degrees.188///189/// It is possible to get the angle by taking the arc cosine (`acos`) of the dot product. It is190/// often unnecessary to do this though. Beware than `acos` will return `NaN` if the input is less191/// than -1.0 or greater than 1.0. This can happen even when working with unit vectors due to192/// floating point precision loss, so it pays to clamp your dot product value before calling193/// `acos`.194fn rotate_to_player_system(195time: Res<Time>,196mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,197player_transform: Single<&Transform, With<Player>>,198) {199// Get the player translation in 2D200let player_translation = player_transform.translation.xy();201202for (config, mut enemy_transform) in &mut query {203// Get the enemy ship forward vector in 2D (already unit length)204let enemy_forward = (enemy_transform.rotation * Vec3::Y).xy();205206// Get the vector from the enemy ship to the player ship in 2D and normalize it.207let to_player = (player_translation - enemy_transform.translation.xy()).normalize();208209// Get the dot product between the enemy forward vector and the direction to the player.210let forward_dot_player = enemy_forward.dot(to_player);211212// If the dot product is approximately 1.0 then the enemy is already facing the player and213// we can early out.214if (forward_dot_player - 1.0).abs() < f32::EPSILON {215continue;216}217218// Get the right vector of the enemy ship in 2D (already unit length)219let enemy_right = (enemy_transform.rotation * Vec3::X).xy();220221// Get the dot product of the enemy right vector and the direction to the player ship.222// If the dot product is negative them we need to rotate counter clockwise, if it is223// positive we need to rotate clockwise. Note that `copysign` will still return 1.0 if the224// dot product is 0.0 (because the player is directly behind the enemy, so perpendicular225// with the right vector).226let right_dot_player = enemy_right.dot(to_player);227228// Determine the sign of rotation from the right dot player. We need to negate the sign229// here as the 2D bevy co-ordinate system rotates around +Z, which is pointing out of the230// screen. Due to the right hand rule, positive rotation around +Z is counter clockwise and231// negative is clockwise.232let rotation_sign = -f32::copysign(1.0, right_dot_player);233234// Limit rotation so we don't overshoot the target. We need to convert our dot product to235// an angle here so we can get an angle of rotation to clamp against.236let max_angle = ops::acos(forward_dot_player.clamp(-1.0, 1.0)); // Clamp acos for safety237238// Calculate angle of rotation with limit239let rotation_angle =240rotation_sign * (config.rotation_speed * time.delta_secs()).min(max_angle);241242// Rotate the enemy to face the player243enemy_transform.rotate_z(rotation_angle);244}245}246247248