game.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. use bevy::prelude::*;
  2. use crate::components as c;
  3. pub fn setup(mut commands: Commands, mut materials: ResMut<Assets<ColorMaterial>>) {
  4. commands.spawn_bundle(OrthographicCameraBundle::new_2d());
  5. commands.insert_resource(c::Materials {
  6. head_material: materials.add(Color::rgb(0.7, 0.7, 0.7).into()),
  7. segment_material: materials.add(Color::rgb(0.3, 0.3, 0.3).into()),
  8. food_material: materials.add(Color::rgb(1.0, 0.0, 1.0).into()),
  9. });
  10. }
  11. pub fn size_scaling(windows: Res<Windows>, mut q: Query<(&c::GridSize, &mut Sprite)>) {
  12. let window = windows.get_primary().unwrap();
  13. for (size, mut sprite) in q.iter_mut() {
  14. sprite.size = Vec2::new(
  15. size.width / c::ARENA_WIDTH as f32 * window.width() as f32,
  16. size.height / c::ARENA_HEIGHT as f32 * window.height() as f32,
  17. );
  18. }
  19. }
  20. pub fn position_translation(windows: Res<Windows>, mut q: Query<(&c::Position, &mut Transform)>) {
  21. fn convert(pos: f32, bound_window: f32, bound_game: f32) -> f32 {
  22. let tile_size = bound_window / bound_game;
  23. pos / bound_game * bound_window - (bound_window / 2.0) + (tile_size / 2.0)
  24. }
  25. let window = windows.get_primary().unwrap();
  26. for (pos, mut tf) in q.iter_mut() {
  27. tf.translation = Vec3::new(
  28. convert(pos.x as f32, window.width() as f32, c::ARENA_WIDTH as f32),
  29. convert(pos.y as f32, window.height() as f32, c::ARENA_HEIGHT as f32),
  30. 0.0,
  31. )
  32. }
  33. }