docs/bevy/examples/3d/texture.rs 2.5 K · 78 lines · raw · history

1 //! This example shows various ways to configure texture materials in 3D.
2
3 use std::f32::consts::PI;
4
5 use bevy::prelude::*;
6
7 fn main() {
8 App::new()
9 .add_plugins(DefaultPlugins)
10 .add_systems(Startup, setup)
11 .run();
12 }
13
14 /// sets up a scene with textured entities
15 fn setup(
16 mut commands: Commands,
17 asset_server: Res<AssetServer>,
18 mut meshes: ResMut<Assets<Mesh>>,
19 mut materials: ResMut<Assets<StandardMaterial>>,
20 ) {
21 // load a texture and retrieve its aspect ratio
22 let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
23 let aspect = 0.25;
24
25 // create a new quad mesh. this is what we will apply the texture to
26 let quad_width = 8.0;
27 let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
28
29 // this material renders the texture normally
30 let material_handle = materials.add(StandardMaterial {
31 base_color_texture: Some(texture_handle.clone()),
32 alpha_mode: AlphaMode::Blend,
33 unlit: true,
34 ..default()
35 });
36
37 // this material modulates the texture to make it red (and slightly transparent)
38 let red_material_handle = materials.add(StandardMaterial {
39 base_color: Color::srgba(1.0, 0.0, 0.0, 0.5),
40 base_color_texture: Some(texture_handle.clone()),
41 alpha_mode: AlphaMode::Blend,
42 unlit: true,
43 ..default()
44 });
45
46 // and lets make this one blue! (and also slightly transparent)
47 let blue_material_handle = materials.add(StandardMaterial {
48 base_color: Color::srgba(0.0, 0.0, 1.0, 0.5),
49 base_color_texture: Some(texture_handle),
50 alpha_mode: AlphaMode::Blend,
51 unlit: true,
52 ..default()
53 });
54
55 // textured quad - normal
56 commands.spawn((
57 Mesh3d(quad_handle.clone()),
58 MeshMaterial3d(material_handle),
59 Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
60 ));
61 // textured quad - modulated
62 commands.spawn((
63 Mesh3d(quad_handle.clone()),
64 MeshMaterial3d(red_material_handle),
65 Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
66 ));
67 // textured quad - modulated
68 commands.spawn((
69 Mesh3d(quad_handle),
70 MeshMaterial3d(blue_material_handle),
71 Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
72 ));
73 // camera
74 commands.spawn((
75 Camera3d::default(),
76 Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
77 ));
78 }