grid system basics
This commit is contained in:
parent
1f389f5285
commit
b45c2e88c8
4 changed files with 68 additions and 0 deletions
67
src/grid.rs
67
src/grid.rs
|
|
@ -1,3 +1,70 @@
|
|||
use bevy::prelude::*;
|
||||
|
||||
use crate::{animation::transform::AnimatedTransform, card::drag::MousePosition};
|
||||
|
||||
pub struct GridPlugin;
|
||||
|
||||
impl Plugin for GridPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Startup, setup_grid)
|
||||
.add_systems(Update, snap_grid_elements);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct Grid {
|
||||
bounds: Rect,
|
||||
columns: usize,
|
||||
rows: usize,
|
||||
elements: Vec<Option<Entity>>,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
pub fn square(start: Vec2, side: f32, cells: usize) -> Self {
|
||||
let mut elements: Vec<Option<Entity>> = Vec::new();
|
||||
elements.resize(cells * cells, None);
|
||||
Grid {
|
||||
bounds: Rect {
|
||||
min: start,
|
||||
max: start + Vec2::new(side * (cells as f32), side * (cells as f32)),
|
||||
},
|
||||
columns: cells,
|
||||
rows: cells,
|
||||
elements: elements,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_position(&self, index: usize) -> Vec3 {
|
||||
let x = index % self.columns;
|
||||
let y = (index / self.columns).clamp(0, self.rows - 1);
|
||||
|
||||
(self.bounds.min + self.cell_size() / 2. + vec2(x as f32, y as f32) * self.cell_size())
|
||||
.extend(0.)
|
||||
}
|
||||
|
||||
fn cell_size(&self) -> Vec2 {
|
||||
self.bounds.size() / vec2(self.columns as f32, -(self.rows as f32))
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_grid(mut commands: Commands) {
|
||||
commands.spawn(Grid::square(vec2(-244., 192.), 80., 5));
|
||||
}
|
||||
|
||||
fn snap_grid_elements(
|
||||
mut transform_query: Query<&mut AnimatedTransform>,
|
||||
grid_query: Query<&Grid>,
|
||||
) {
|
||||
for grid in grid_query {
|
||||
for (index, el) in grid.elements.iter().enumerate() {
|
||||
let Some(entity) = el else {
|
||||
continue;
|
||||
};
|
||||
let Ok(mut transform) = transform_query.get_mut(entity.clone()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
transform.translation = grid.get_position(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ fn main() {
|
|||
card::CardPlugin,
|
||||
DefaultPlugins,
|
||||
dev_tools::DevToolsPlugin,
|
||||
grid::GridPlugin,
|
||||
turns::TurnSystemPlugin,
|
||||
))
|
||||
.add_systems(Startup, setup)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue