Skip to content

Instantly share code, notes, and snippets.

@rparrett
Last active July 14, 2024 18:03
Show Gist options
  • Save rparrett/30a77d5917c869ed4204e9f61770ee51 to your computer and use it in GitHub Desktop.
Save rparrett/30a77d5917c869ed4204e9f61770ee51 to your computer and use it in GitHub Desktop.
Bevy 0.12 2d Repeating Image
use bevy::{
prelude::*,
render::{
mesh::VertexAttributeValues,
texture::{ImageAddressMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor},
},
sprite::MaterialMesh2dBundle,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
asset_server: Res<AssetServer>,
) {
commands.spawn(Camera2dBundle::default());
let texture = Some(asset_server.load_with_settings(
"branding/icon.png",
|s: &mut ImageLoaderSettings| match &mut s.sampler {
ImageSampler::Default => {
s.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
address_mode_u: ImageAddressMode::Repeat,
address_mode_v: ImageAddressMode::Repeat,
..default()
});
}
ImageSampler::Descriptor(sampler) => {
sampler.address_mode_u = ImageAddressMode::Repeat;
sampler.address_mode_v = ImageAddressMode::Repeat;
}
},
));
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(repeating_quad(10.)).into(),
material: materials.add(ColorMaterial {
texture,
..default()
}),
transform: Transform::from_translation(Vec3::new(0., 0., -10.))
.with_scale(Vec2::splat(1000.).extend(1.)),
..default()
});
}
fn repeating_quad(n: f32) -> Mesh {
let mut mesh: Mesh = shape::Quad::default().into();
let uv_attribute = mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0).unwrap();
// The format of the UV coordinates should be Float32x2.
let VertexAttributeValues::Float32x2(uv_attribute) = uv_attribute else {
panic!("Unexpected vertex format, expected Float32x2.");
};
// The default `Quad`'s texture coordinates are in the range of `0..=1`. Values outside
// this range cause the texture to repeat.
for uv_coord in uv_attribute.iter_mut() {
uv_coord[0] = uv_coord[0] * n;
uv_coord[1] = uv_coord[1] * n;
}
mesh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment