Skip to content

Instantly share code, notes, and snippets.

@rparrett
Last active January 23, 2025 15:24
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.15 2d Repeating Image
use bevy::{
image::{ImageAddressMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor},
prelude::*,
render::mesh::VertexAttributeValues,
};
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(Camera2d);
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((
Mesh2d(meshes.add(repeating_quad(10.))),
MeshMaterial2d(materials.add(ColorMaterial {
texture,
..default()
})),
Transform::from_translation(Vec3::new(0., 0., -10.))
.with_scale(Vec2::splat(1000.).extend(1.)),
));
}
fn repeating_quad(n: f32) -> Mesh {
let mut mesh: Mesh = Rectangle::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 `Rectangle`'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] *= n;
uv_coord[1] *= n;
}
mesh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment