Skip to content

Instantly share code, notes, and snippets.

@cart
Last active February 5, 2024 15:18
Show Gist options
  • Save cart/87c0215aa650170f09164fcffc252139 to your computer and use it in GitHub Desktop.
Save cart/87c0215aa650170f09164fcffc252139 to your computer and use it in GitHub Desktop.
Basic Letterboxing
use bevy::{
core_pipeline::clear_color::ClearColorConfig,
prelude::*,
render::{camera::RenderTarget, render_resource::*},
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.run();
}
/// set up a simple 3D scene
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
mut images: ResMut<Assets<Image>>,
) {
// The size of the rendered area
let size = Extent3d {
width: 400,
height: 300,
..default()
};
// This is the texture that will be rendered to
let mut image = Image {
texture_descriptor: TextureDescriptor {
label: None,
size,
dimension: TextureDimension::D2,
format: TextureFormat::Bgra8UnormSrgb,
mip_level_count: 1,
sample_count: 1,
usage: TextureUsages::TEXTURE_BINDING
| TextureUsages::COPY_DST
| TextureUsages::RENDER_ATTACHMENT,
},
..default()
};
// fill image.data with zeroes
image.resize(size);
let image_handle = images.add(image);
// Main Camera
commands
.spawn_bundle(Camera2dBundle {
camera: Camera {
priority: -1,
target: RenderTarget::Image(image_handle.clone()),
..default()
},
..default()
})
// UI is assumed to be done on the "full sized primary window", so Bevy can't yet meaningfully render it to
// a smaller image. This will be improved soon.
.insert(CameraUi { is_enabled: false });
// This is a lame hack to get "full screen full size" UI. We won't actually be drawing anything in 3d.
// TODO: replace this with a Camera2dBundle with RenderLayers::none() once sprites have been ported to the render layers system
commands.spawn_bundle(Camera3dBundle {
camera_3d: Camera3d {
clear_color: ClearColorConfig::Custom(Color::rgb(0.1, 0.1, 0.1)),
..default()
},
..default()
});
commands.spawn_bundle(ImageBundle {
style: Style {
size: Size::new(Val::Auto, Val::Auto),
margin: UiRect::all(Val::Auto),
..default()
},
image: image_handle.into(),
..default()
});
let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
let texture_atlas = TextureAtlas::from_grid(texture_handle, Vec2::new(24.0, 24.0), 7, 1);
let texture_atlas_handle = texture_atlases.add(texture_atlas);
// Spawn sprite
commands.spawn_bundle(SpriteSheetBundle {
texture_atlas: texture_atlas_handle,
..default()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment