Skip to content

Instantly share code, notes, and snippets.

@ciwolsey
Created July 4, 2022 16:41
Show Gist options
  • Save ciwolsey/38304289e2606db55b1008c21a276f4f to your computer and use it in GitHub Desktop.
Save ciwolsey/38304289e2606db55b1008c21a276f4f to your computer and use it in GitHub Desktop.
use bevy::prelude::*;
fn main() {
App::new()
.insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0)))
.insert_resource(WindowDescriptor {
title: "Grid".into(),
width: 750.0,
height: 750.0,
..Default::default()
})
.insert_resource(Msaa { samples: 4 })
.add_plugins(DefaultPlugins)
.add_startup_system_to_stage(StartupStage::Startup, setup_system)
.add_system(draw)
//.add_startup_system_to_stage(StartupStage::PostStartup, draw_grid)
.run();
}
#[derive(Component, Clone, Debug)]
struct Grid {
spacing: Vec2,
z_rotation: f32,
matrix: Mat4,
}
enum GridAlign {
BottomLeft,
BottomRight,
TopLeft,
TopRight,
Center,
NotImplemented,
}
struct GridPosition {
alignment: GridAlign,
position: Vec3,
}
impl Grid {
fn new(spacing: Vec2, scale: Vec3, z_rotation: f32) -> Self {
Self {
spacing,
z_rotation,
matrix: Mat4::from_scale(scale) * Mat4::from_rotation_z(z_rotation),
}
}
fn Position(&self, x: i32, y: i32, grid_align: GridAlign) -> Vec3 {
let pos = match grid_align {
GridAlign::BottomLeft => {
Vec3::new(x as f32 * self.spacing.x, y as f32 * self.spacing.y, 0.0)
}
GridAlign::Center => Vec3::new(
(x as f32 * self.spacing.x) + (self.spacing.x * 0.5),
(y as f32 * self.spacing.y) + (self.spacing.y * 0.5),
0.0,
),
GridAlign::BottomRight => Vec3::new(
(x as f32 * self.spacing.x) + (self.spacing.x),
(y as f32 * self.spacing.y),
0.0,
),
_ => Vec3::new(x as f32 * self.spacing.x, y as f32 * self.spacing.y, 0.0),
};
self.matrix.transform_point3(pos)
}
}
fn setup_system(mut commands: Commands, asset_server: Res<AssetServer>) {
let grid = Grid::new(
Vec2::new(50.0, 50.0),
Vec3::ONE - (Vec3::Y * 0.35),
0.7853982,
);
commands.insert_resource(grid.clone());
// Bevy 0.7
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
// Bevy 0.8
// commands.spawn_bundle(Camera2dBundle::default());
}
fn draw(mut commands: Commands, asset_server: Res<AssetServer>, grid: Res<Grid>) {
commands.spawn_bundle(SpriteBundle {
transform: Transform {
translation: grid.Position(0, 0, GridAlign::BottomLeft) + (Vec3::Z * 5.0),
rotation: Quat::from_rotation_z(0.0),
scale: Vec3::new(1., 1., 1.),
..Default::default()
},
sprite: Sprite {
//custom_size: Some(Vec2::new(1.0, 1.0)),
..Default::default()
},
texture: asset_server.load("iso2.png"),
..Default::default()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment