feat: make camera follow player

Former-commit-id: d13b9416c74308eaf9df81b431b82152b7a20510
This commit is contained in:
Muhammad Nauman Raza 2023-12-06 13:35:53 +00:00
parent 0a57befd3c
commit c7203fa9ed
Signed by: devraza
GPG key ID: 91EAD6081011574B
3 changed files with 33 additions and 19 deletions

View file

@ -55,7 +55,7 @@ fn main() {
.init_resource::<UiState>()
.init_resource::<OpenWindows>()
.add_systems(Startup, (setup, setup_ui))
.add_systems(Update, (render_ui, movement))
.add_systems(Update, (render_ui, movement, camera_follow))
.run();
}
@ -69,6 +69,15 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
tonemapping: Tonemapping::TonyMcMapface,
..default()
});
commands.spawn(
SpriteBundle {
texture: asset_server.load("player/player-4x.png"),
transform: Transform {
scale: Vec3::splat(0.2),
..default()
},
..default()
});
commands.spawn((
SpriteBundle {
texture: asset_server.load("player/player-4x.png"),

View file

@ -18,10 +18,9 @@ pub struct Player {
pub fn movement(
time: Res<Time>,
keys: Res<Input<KeyCode>>,
mut windows: Query<&mut Window>,
mut query: Query<(&Player, &mut Transform)>,
mut player: Query<(&Player, &mut Transform)>,
) {
let (player, mut transform) = query.single_mut();
let (player, mut transform) = player.single_mut();
let mut rotation_factor = 0.;
let mut movement_factor = 0.;
@ -76,12 +75,18 @@ pub fn movement(
// Update the player translation with the translation
transform.translation += movement_direction * movement_distance;
// Define the bounds of play (the window size)
let window = windows.single_mut();
let bounds = Vec3::from((
Vec2::new(window.resolution.width(), window.resolution.height()) / 2.,
0.,
));
transform.translation = transform.translation.min(bounds).max(-bounds);
}
// Function to make the camera follow the plaeyr
pub fn camera_follow(
mut player: Query<(&Player, &mut Transform)>,
mut cameras: Query<&mut Transform, (With<Camera>, Without<Player>)>,
) {
let (_, transform) = player.single_mut();
let pos = transform.translation;
for mut camera_transform in &mut cameras {
camera_transform.translation.x = pos.x;
camera_transform.translation.y = pos.y;
}
}

View file

@ -2,8 +2,8 @@ use bevy::prelude::*;
use bevy_egui::{egui, EguiContexts};
use crate::HYPERNOVA;
use crate::Player;
use crate::HYPERNOVA;
// Define UI resources
#[derive(Default, Resource)]
@ -111,10 +111,10 @@ pub fn render_ui(
ui.visuals_mut().menu_rounding = egui::Rounding::ZERO;
ui.visuals_mut().selection.bg_fill = purple;
let health = egui::widgets::ProgressBar::new(player.health)
.desired_width(window_width / 10.);
let stamina = egui::widgets::ProgressBar::new(player.stamina)
.desired_width(window_width / 10.);
let health =
egui::widgets::ProgressBar::new(player.health).desired_width(window_width / 10.);
let stamina =
egui::widgets::ProgressBar::new(player.stamina).desired_width(window_width / 10.);
egui::Grid::new("Stats")
.spacing(egui::Vec2::new(20., 10.))