Skip to content

Instantly share code, notes, and snippets.

@BrettWitty
Last active September 1, 2020 12:08
Show Gist options
  • Save BrettWitty/4fe9694a6f546e044dff3ae7d25e5dd4 to your computer and use it in GitHub Desktop.
Save BrettWitty/4fe9694a6f546e044dff3ae7d25e5dd4 to your computer and use it in GitHub Desktop.
Weird bug in Bevy example
use bevy::prelude::*;
use bevy::render::pass::ClearColor;
const WIDTH: u32 = 16;
const HEIGHT: u32 = 16;
struct Tile {
x: u32,
y: u32
}
#[derive(Default)]
struct CurrentTile {
i: u32,
j: u32,
triggered: bool
}
fn create_tiles(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<ColorMaterial>>
) {
commands.spawn(Camera2dComponents::default());
// A 64x64 png.
let texture_handle = asset_server.load("data/icon.png").unwrap();
for i in 0..HEIGHT {
for j in 0..WIDTH {
commands.spawn(SpriteComponents {
material: materials.add(texture_handle.into()),
translation: Translation::new(
(i as f32)*64.0 - ((WIDTH -1) as f32)*32.0,
(j as f32)*64.0 - ((HEIGHT -1) as f32)*32.0,
0.0
),
..Default::default()
})
.with(Tile { x: i, y: j})
.with(Timer::from_seconds(0.1,true));
}
}
}
fn animate(
mut cur_tile: ResMut<CurrentTile>,
mut query: Query<(&mut Timer, &Tile, &mut Draw)>
) {
cur_tile.triggered = false;
for (mut timer, tile, mut draw) in &mut query.iter() {
if timer.finished {
if !cur_tile.triggered {
if (cur_tile.i == tile.x) && (cur_tile.j == tile.y) {
println!("Tile {}x{}", cur_tile.i, cur_tile.j);
draw.is_visible = !draw.is_visible;
cur_tile.triggered = true;
cur_tile.i += 1;
if cur_tile.i >= WIDTH {
cur_tile.i %= WIDTH;
cur_tile.j += 1;
cur_tile.j %= HEIGHT;
}
}
}
timer.reset();
}
}
}
fn main() {
App::build()
.add_resource( WindowDescriptor {
title: "Lotsa tiles".to_string(),
width: WIDTH*64,
height: HEIGHT*64,
resizable: false,
..Default::default()
})
.add_resource(ClearColor(Color::rgb(1.0,0.72,0.0588)))
.init_resource::<CurrentTile>()
.add_startup_system(create_tiles.system())
.add_default_plugins()
.add_system(animate.system())
.run();
}
@BrettWitty
Copy link
Author

Something beautiful but bizarre is happening here. I can't tell if it's a bevy bug or a bug in my brain.

The intent is that we have 16x16 tiles (each tile 64x64 pixels). Every 0.1 second, it flips the current tile's visibility, then moves to the next (iterating over x then y).

Every timestep should modify exactly one sprite, but it appears to modify two. I can't see how unless query.iter() is run in parallel and there's some race condition in CurrentTile. Or I've made some very silly mistake.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment