diff --git a/Cargo.lock b/Cargo.lock index 0deef6f..ff8b136 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,6 +541,7 @@ dependencies = [ "fnv", "gamedebug_core", "hecs", + "num-traits", "rand", "rfd", "s2dc", diff --git a/Cargo.toml b/Cargo.toml index 63ce3d9..427187f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ anyhow = "1.0.70" egui-sfml = "0.4.0" fnv = "1.0.7" hecs = "0.10.1" +num-traits = "0.2.15" rand = "0.8.5" rfd = "0.11.3" sfml = "0.20.0" diff --git a/src/app.rs b/src/app.rs index 4fa6aca..b1431ce 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,7 +16,7 @@ use crate::{ game::{for_each_tile_on_screen, Biome, GameState}, graphics::{self, ScreenPosScalar, NATIVE_RESOLUTION}, input::Input, - math::{px_per_frame_to_km_h, WorldPos, M_PER_PX, TILE_SIZE}, + math::{center_offset, px_per_frame_to_km_h, WorldPos, M_PER_PX, TILE_SIZE}, res::Res, world::{Tile, TilePosScalar, CHUNK_EXTENT}, }; @@ -243,6 +243,11 @@ impl App { self.rt.display(); let mut spr = Sprite::with_texture(self.rt.texture()); spr.set_scale((self.scale as f32, self.scale as f32)); + let rw_size = self.rw.size(); + let rt_size = self.rt.size() * self.scale as u32; + let x = center_offset(rt_size.x as i32, rw_size.x as i32); + let y = center_offset(rt_size.y as i32, rw_size.y as i32); + spr.set_position((x as f32, y as f32)); self.rw.clear(Color::rgb(40, 10, 70)); self.rw.draw(&spr); self.sf_egui diff --git a/src/math.rs b/src/math.rs index ea4611f..7cf8cc0 100644 --- a/src/math.rs +++ b/src/math.rs @@ -1,3 +1,5 @@ +use num_traits::Signed; + use crate::world::{TilePos, TilePosScalar}; pub type WorldPosScalar = u32; @@ -50,6 +52,23 @@ pub fn wp_to_tp(wp: WorldPosScalar) -> TilePosScalar { (wp / TILE_SIZE as WorldPosScalar) as TilePosScalar } +// Get the offset required to center an object of `xw` width inside an object of `yw` width. +// +// For example, let's say `xw` (+) is 10 and we want to center it inside `yw` (-), which is 20 +// +// ++++++++++ (x uncentered) +// -------------------- (y) +// ++++++++++ (x centered) +// +// In this case, we needed to add 5 to x to achieve centering. +// This is the offset that this function calculates. +// +// We can calulate it by subtracting `xw` from `yw` (10), and dividing it by 2. +pub fn center_offset + Copy + Signed>(xw: N, yw: N) -> N { + let diff = yw - xw; + diff / N::from(2) +} + #[test] fn test_wp_to_tp() { assert_eq!(wp_to_tp(0), 0);