Clearing the screen every frame #9205
-
I am trying to move a box around on the screen. Every Here's a stripped down, runable version of what I have: use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
#[derive(Component)]
struct Location(Vec2);
fn setup(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
commands.spawn(Location(Vec2 { x: 0., y: 0. }));
}
fn draw(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
mut query: Query<&mut Location>,
) {
for mut location in &mut query {
location.0.x += 10.;
commands.spawn(MaterialMesh2dBundle {
mesh: meshes
.add(Mesh::from(shape::Quad::new(Vec2::splat(5.))))
.into(),
material: materials.add(ColorMaterial::from(Color::TEAL)),
transform: Transform {
translation: Vec3::from((location.0, 0.)),
..default()
},
..default()
});
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(ClearColor(Color::WHITE))
.add_systems(Startup, setup)
.add_systems(Update, draw)
.run();
} It draws a 5x5 square every frame (loop? not sure if that's the right word) moves it by 10 to the right, then draw's it again. Here's what is looks like after a bunch of frames: How can I get the previously drawn squares to disappear each redraw so I can make it look like a single square is moving on the screen? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This code spawns multiple |
Beta Was this translation helpful? Give feedback.
-
Hi, you are spawning new entity with mesh and material every loop in the for loop - notice the And then you need to add the Also your |
Beta Was this translation helpful? Give feedback.
Hi, you are spawning new entity with mesh and material every loop in the for loop - notice the
commands.spawn
- and entities unless removed are persistent during runtime. So from thedraw
system remove the wholecommands.spawn
.And then you need to add the
MaterialMesh2Bundle
to thesetup
system. You are already spawning new entity there so add the bundle to that location entity.Also your
Location
component is redundant becauseTransform
andGlobalTransform
, which are added byMaterialMesh2Bundle
, are Bevy's default position components.