//! Demonstrates rotating sprites to face the cursor.12use bevy::prelude::*;3use std::f32::consts::FRAC_PI_2;45fn main() {6App::new()7.add_plugins(DefaultPlugins)8.add_systems(Startup, setup)9.add_systems(FixedUpdate, player_movement_system)10.run();11}1213/// Player component14#[derive(Component)]15struct Player;1617/// Add the game's entities to our world and create an orthographic camera for 2D rendering.18///19/// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:20///21/// * `X` axis goes from left to right (`+X` points right)22/// * `Y` axis goes from bottom to top (`+Y` point up)23/// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)24///25/// The world origin in this case is at the center of the screen, but the camera could26/// move in which case the world origin would not be the center of the screen27fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {28let ship_handle = asset_server.load("textures/simplespace/ship_C.png");2930commands.spawn(Camera2d);3132// Player controlled ship33commands.spawn((Sprite::from_image(ship_handle), Player));34}3536/// Demonstrates applying rotation and movement based on keyboard input.37fn player_movement_system(38mut player: Single<&mut Transform, With<Player>>,39camera_query: Single<(&Camera, &GlobalTransform)>,40window: Single<&Window>,41) {42let (camera, camera_transform) = *camera_query;4344if let Some(cursor_position) = window.cursor_position()45// Calculate a world position based on the cursor's position.46&& let Ok(cursor_world_pos) = camera.viewport_to_world_2d(camera_transform, cursor_position)47{48// The angle an entity needs to rotate to face a point is defined49// by the vector between the two points (Vec2 - Vec2), which we can then50// turn into radians using to_angle.51//52// FRAC_PI_2 is because our sprite's ship is facing "up" so we rotate it an additional 90 degrees53// so that it faces the cursor.54player.rotation = Quat::from_rotation_z(55(cursor_world_pos - player.translation.xy()).to_angle() - FRAC_PI_2,56);57}58}596061