Struct bevy::transform::components::Transform
pub struct Transform {
pub translation: Vec3,
pub rotation: Quat,
pub scale: Vec3,
}
Expand description
Describe the position of an entity. If the entity has a parent, the position is relative to its parent position.
- To place or move an entity, you should set its
Transform
. - To get the global transform of an entity, you should get its
GlobalTransform
. - To be displayed, an entity must have both a
Transform
and aGlobalTransform
.- You may use the
TransformBundle
to guarantee this.
- You may use the
§Transform
and GlobalTransform
Transform
is the position of an entity relative to its parent position, or the reference
frame if it doesn’t have a Parent
.
GlobalTransform
is the position of an entity relative to the reference frame.
GlobalTransform
is updated from Transform
by systems in the system set
TransformPropagate
.
This system runs during PostUpdate
. If you
update the Transform
of an entity during this set or after, you will notice a 1 frame lag
before the GlobalTransform
is updated.
§Examples
Fields§
§translation: Vec3
Position of the entity. In 2d, the last value of the Vec3
is used for z-ordering.
See the translations
example for usage.
rotation: Quat
Rotation of the entity.
See the 3d_rotation
example for usage.
scale: Vec3
Scale of the entity.
See the scale
example for usage.
Implementations§
§impl Transform
impl Transform
pub const IDENTITY: Transform = _
pub const IDENTITY: Transform = _
An identity Transform
with no translation, rotation, and a scale of 1 on all axes.
pub const fn from_xyz(x: f32, y: f32, z: f32) -> Transform
pub const fn from_xyz(x: f32, y: f32, z: f32) -> Transform
Creates a new Transform
at the position (x, y, z)
. In 2d, the z
component
is used for z-ordering elements: higher z
-value will be in front of lower
z
-value.
Examples found in repository?
More examples
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
fn spawn_camera(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(Camera3dBundle {
transform: Transform::from_xyz(-10.012, 4.8605, 13.281).looking_at(Vec3::ZERO, Vec3::Y),
..default()
})
.insert(Skybox {
image: assets.skybox.clone(),
brightness: 150.0,
});
}
fn spawn_irradiance_volume(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(SpatialBundle {
transform: Transform::from_matrix(VOXEL_TRANSFORM),
..SpatialBundle::default()
})
.insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
})
.insert(LightProbe);
}
fn spawn_light(commands: &mut Commands) {
commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 250000.0,
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0762, 5.9039, 1.0055),
..default()
});
}
fn spawn_sphere(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(PbrBundle {
mesh: assets.main_sphere.clone(),
material: assets.main_sphere_material.clone(),
transform: Transform::from_xyz(0.0, SPHERE_SCALE, 0.0)
.with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(MainObject);
}
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
fn setup(mut commands: Commands) {
warn!(include_str!("warning_string.txt"));
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(3., 1., 5.).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
commands.spawn(TextBundle::from_section(
"",
TextStyle {
font_size: 30.,
..default()
},
));
}
20 21 22 23 24 25 26 27 28 29 30 31 32
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Create a camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// Spawn the first scene in `models/SimpleSkin/SimpleSkin.gltf`
commands.spawn(SceneBundle {
scene: asset_server.load("models/SimpleSkin/SimpleSkin.gltf#Scene0"),
..default()
});
}
- examples/games/alien_cake_addict.rs
- examples/math/render_primitives.rs
- examples/shader/animate_shader.rs
- examples/async_tasks/external_source_external_thread.rs
- examples/shader/array_texture.rs
- examples/shader/fallback_image.rs
- examples/shader/shader_material.rs
- examples/3d/3d_viewport_to_world.rs
- examples/animation/morph_targets.rs
- examples/shader/texture_binding_array.rs
- examples/2d/pixel_grid_snap.rs
- examples/shader/custom_vertex_attribute.rs
- examples/2d/transparency_2d.rs
- examples/transforms/3d_rotation.rs
- examples/3d/atmospheric_fog.rs
- examples/transforms/scale.rs
- examples/transforms/translation.rs
- examples/shader/shader_defs.rs
- tests/window/minimising.rs
- tests/window/resizing.rs
- examples/3d/tonemapping.rs
- examples/3d/animated_material.rs
- examples/3d/3d_scene.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/shader/post_processing.rs
- examples/3d/skybox.rs
- examples/3d/parenting.rs
- examples/3d/lines.rs
- examples/3d/load_gltf.rs
- examples/2d/2d_shapes.rs
- examples/3d/two_passes.rs
- examples/3d/update_gltf_scene.rs
- examples/shader/shader_instancing.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/animation/cubic_curve.rs
- examples/ecs/hierarchy.rs
- examples/shader/extended_material.rs
- examples/3d/vertex_colors.rs
- examples/3d/orthographic.rs
- examples/3d/generate_custom_mesh.rs
- examples/window/multiple_windows.rs
- examples/3d/3d_shapes.rs
- examples/transforms/transform.rs
- examples/3d/spherical_area_lights.rs
- examples/animation/animated_fox.rs
- examples/3d/3d_gizmos.rs
- examples/games/contributors.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/3d/wireframe.rs
- examples/2d/rotation.rs
- examples/window/low_power.rs
- examples/audio/spatial_audio_2d.rs
- examples/3d/fog.rs
- examples/audio/spatial_audio_3d.rs
- examples/2d/bounding_2d.rs
- examples/3d/texture.rs
- examples/3d/ssao.rs
- examples/async_tasks/async_compute.rs
- examples/3d/bloom_3d.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/transparency_3d.rs
- examples/ecs/iter_combinations.rs
- examples/3d/anti_aliasing.rs
- examples/ui/render_ui_to_texture.rs
- examples/3d/spotlight.rs
- examples/2d/sprite_slice.rs
- examples/asset/asset_loading.rs
- examples/3d/pbr.rs
- examples/3d/render_to_texture.rs
- examples/stress_tests/many_foxes.rs
- examples/shader/shader_prepass.rs
- examples/stress_tests/many_cubes.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/parallax_mapping.rs
- examples/3d/split_screen.rs
- examples/animation/animated_transform.rs
- examples/3d/shadow_biases.rs
- examples/3d/deferred_rendering.rs
- examples/3d/blend_modes.rs
- examples/3d/lighting.rs
- examples/3d/transmission.rs
pub fn from_matrix(matrix: Mat4) -> Transform
pub fn from_matrix(matrix: Mat4) -> Transform
Extracts the translation, rotation, and scale from matrix
. It must be a 3d affine
transformation matrix.
Examples found in repository?
243 244 245 246 247 248 249 250 251 252 253 254
fn spawn_irradiance_volume(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(SpatialBundle {
transform: Transform::from_matrix(VOXEL_TRANSFORM),
..SpatialBundle::default()
})
.insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
})
.insert(LightProbe);
}
pub const fn from_translation(translation: Vec3) -> Transform
pub const fn from_translation(translation: Vec3) -> Transform
Creates a new Transform
, with translation
. Rotation will be 0 and scale 1 on
all axes.
Examples found in repository?
More examples
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
fn setup_lights(mut commands: Commands) {
commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 5000.0,
..default()
},
transform: Transform::from_translation(Vec3::new(-LEFT_RIGHT_OFFSET_3D, 2.0, 0.0))
.looking_at(Vec3::new(-LEFT_RIGHT_OFFSET_3D, 0.0, 0.0), Vec3::Y),
..default()
});
}
/// Marker component for header text
#[derive(Debug, Clone, Component, Default, Reflect)]
pub struct HeaderText;
/// Marker component for header node
#[derive(Debug, Clone, Component, Default, Reflect)]
pub struct HeaderNode;
fn update_active_cameras(
state: Res<State<CameraActive>>,
mut camera_2d: Query<(Entity, &mut Camera), With<Camera2d>>,
mut camera_3d: Query<(Entity, &mut Camera), (With<Camera3d>, Without<Camera2d>)>,
mut text: Query<&mut TargetCamera, With<HeaderNode>>,
) {
let (entity_2d, mut cam_2d) = camera_2d.single_mut();
let (entity_3d, mut cam_3d) = camera_3d.single_mut();
let is_camera_2d_active = matches!(*state.get(), CameraActive::Dim2);
cam_2d.is_active = is_camera_2d_active;
cam_3d.is_active = !is_camera_2d_active;
let active_camera = if is_camera_2d_active {
entity_2d
} else {
entity_3d
};
text.iter_mut().for_each(|mut target_camera| {
*target_camera = TargetCamera(active_camera);
});
}
fn switch_cameras(current: Res<State<CameraActive>>, mut next: ResMut<NextState<CameraActive>>) {
let next_state = match current.get() {
CameraActive::Dim2 => CameraActive::Dim3,
CameraActive::Dim3 => CameraActive::Dim2,
};
next.set(next_state);
}
fn setup_text(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<(Entity, &Camera)>,
) {
let active_camera = cameras
.iter()
.find_map(|(entity, camera)| camera.is_active.then_some(entity))
.expect("run condition ensures existence");
let text = format!("{text}", text = PrimitiveSelected::default());
let font_size = 24.0;
let font: Handle<Font> = asset_server.load("fonts/FiraMono-Medium.ttf");
let style = TextStyle {
font,
font_size,
color: Color::WHITE,
};
let instructions = "Press 'C' to switch between 2D and 3D mode\n\
Press 'Up' or 'Down' to switch to the next/previous primitive";
let text = [
TextSection::new("Primitive: ", style.clone()),
TextSection::new(text, style.clone()),
TextSection::new("\n\n", style.clone()),
TextSection::new(instructions, style.clone()),
TextSection::new("\n\n", style.clone()),
TextSection::new(
"(If nothing is displayed, there's no rendering support yet)",
style.clone(),
),
];
commands
.spawn((
HeaderNode,
NodeBundle {
style: Style {
justify_self: JustifySelf::Center,
top: Val::Px(5.0),
..Default::default()
},
..Default::default()
},
TargetCamera(active_camera),
))
.with_children(|parent| {
parent.spawn((
HeaderText,
TextBundle::from_sections(text).with_text_justify(JustifyText::Center),
));
});
}
fn update_text(
primitive_state: Res<State<PrimitiveSelected>>,
mut header: Query<&mut Text, With<HeaderText>>,
) {
let new_text = format!("{text}", text = primitive_state.get());
header.iter_mut().for_each(|mut header_text| {
if let Some(kind) = header_text.sections.get_mut(1) {
kind.value = new_text.clone();
};
});
}
fn switch_to_next_primitive(
current: Res<State<PrimitiveSelected>>,
mut next: ResMut<NextState<PrimitiveSelected>>,
) {
let next_state = current.get().next();
next.set(next_state);
}
fn switch_to_previous_primitive(
current: Res<State<PrimitiveSelected>>,
mut next: ResMut<NextState<PrimitiveSelected>>,
) {
let next_state = current.get().previous();
next.set(next_state);
}
fn in_mode(active: CameraActive) -> impl Fn(Res<State<CameraActive>>) -> bool {
move |state| *state.get() == active
}
fn draw_gizmos_2d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time: Res<Time>) {
const POSITION: Vec2 = Vec2::new(-LEFT_RIGHT_OFFSET_2D, 0.0);
let angle = time.elapsed_seconds();
let color = Color::WHITE;
match state.get() {
PrimitiveSelected::RectangleAndCuboid => {
gizmos.primitive_2d(RECTANGLE, POSITION, angle, color);
}
PrimitiveSelected::CircleAndSphere => gizmos.primitive_2d(CIRCLE, POSITION, angle, color),
PrimitiveSelected::Ellipse => gizmos.primitive_2d(ELLIPSE, POSITION, angle, color),
PrimitiveSelected::Triangle => gizmos.primitive_2d(TRIANGLE, POSITION, angle, color),
PrimitiveSelected::Plane => gizmos.primitive_2d(PLANE_2D, POSITION, angle, color),
PrimitiveSelected::Line => drop(gizmos.primitive_2d(LINE2D, POSITION, angle, color)),
PrimitiveSelected::Segment => drop(gizmos.primitive_2d(SEGMENT_2D, POSITION, angle, color)),
PrimitiveSelected::Polyline => gizmos.primitive_2d(POLYLINE_2D, POSITION, angle, color),
PrimitiveSelected::Polygon => gizmos.primitive_2d(POLYGON_2D, POSITION, angle, color),
PrimitiveSelected::RegularPolygon => {
gizmos.primitive_2d(REGULAR_POLYGON, POSITION, angle, color);
}
PrimitiveSelected::Capsule => gizmos.primitive_2d(CAPSULE_2D, POSITION, angle, color),
PrimitiveSelected::Cylinder => {}
PrimitiveSelected::Cone => {}
PrimitiveSelected::ConicalFrustrum => {}
PrimitiveSelected::Torus => {}
}
}
/// Marker for primitive meshes to record in which state they should be visible in
#[derive(Debug, Clone, Component, Default, Reflect)]
pub struct PrimitiveData {
camera_mode: CameraActive,
primitive_state: PrimitiveSelected,
}
/// Marker for meshes of 2D primitives
#[derive(Debug, Clone, Component, Default)]
pub struct MeshDim2;
/// Marker for meshes of 3D primitives
#[derive(Debug, Clone, Component, Default)]
pub struct MeshDim3;
fn spawn_primitive_2d(
mut commands: Commands,
mut materials: ResMut<Assets<ColorMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
const POSITION: Vec3 = Vec3::new(LEFT_RIGHT_OFFSET_2D, 0.0, 0.0);
let material: Handle<ColorMaterial> = materials.add(Color::WHITE);
let camera_mode = CameraActive::Dim2;
[
Some(RECTANGLE.mesh()),
Some(CIRCLE.mesh().build()),
Some(ELLIPSE.mesh().build()),
Some(TRIANGLE.mesh()),
None, // plane
None, // line
None, // segment
None, // polyline
None, // polygon
Some(REGULAR_POLYGON.mesh()),
Some(CAPSULE_2D.mesh().build()),
None, // cylinder
None, // cone
None, // conical frustrum
None, // torus
]
.into_iter()
.zip(PrimitiveSelected::ALL)
.for_each(|(maybe_mesh, state)| {
if let Some(mesh) = maybe_mesh {
commands.spawn((
MeshDim2,
PrimitiveData {
camera_mode,
primitive_state: state,
},
MaterialMesh2dBundle {
mesh: meshes.add(mesh).into(),
material: material.clone(),
transform: Transform::from_translation(POSITION),
..Default::default()
},
));
}
});
}
fn spawn_primitive_3d(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
const POSITION: Vec3 = Vec3::new(-LEFT_RIGHT_OFFSET_3D, 0.0, 0.0);
let material: Handle<StandardMaterial> = materials.add(Color::WHITE);
let camera_mode = CameraActive::Dim3;
[
Some(CUBOID.mesh()),
Some(SPHERE.mesh().build()),
None, // ellipse
None, // triangle
Some(PLANE_3D.mesh().build()),
None, // line
None, // segment
None, // polyline
None, // polygon
None, // regular polygon
Some(CAPSULE_3D.mesh().build()),
Some(CYLINDER.mesh().build()),
None, // cone
None, // conical frustrum
Some(TORUS.mesh().build()),
]
.into_iter()
.zip(PrimitiveSelected::ALL)
.for_each(|(maybe_mesh, state)| {
if let Some(mesh) = maybe_mesh {
commands.spawn((
MeshDim3,
PrimitiveData {
camera_mode,
primitive_state: state,
},
PbrBundle {
mesh: meshes.add(mesh),
material: material.clone(),
transform: Transform::from_translation(POSITION),
..Default::default()
},
));
}
});
}
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.spawn((
PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(20., 20.)),
material: materials.add(Color::rgb(0.3, 0.5, 0.3)),
..default()
},
Ground,
));
// light
commands.spawn(DirectionalLightBundle {
transform: Transform::from_translation(Vec3::ONE).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
fn bird_velocity_transform(
half_extents: Vec2,
mut translation: Vec3,
velocity_rng: &mut StdRng,
waves: Option<usize>,
dt: f32,
) -> (Transform, Vec3) {
let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);
if let Some(waves) = waves {
// Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
// and with dt-spaced frames of simulation
for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
step_movement(&mut translation, &mut velocity, dt);
handle_collision(half_extents, &translation, &mut velocity);
}
}
(
Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
velocity,
)
}
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Spawn a cube to rotate.
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: materials.add(Color::WHITE),
transform: Transform::from_translation(Vec3::ZERO),
..default()
},
Rotatable { speed: 0.3 },
));
// Spawn a camera looking at the entities to show what's happening in this example.
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// Add a light source so we can see clearly.
commands.spawn(DirectionalLightBundle {
transform: Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
- examples/transforms/translation.rs
- examples/3d/animated_material.rs
- examples/shader/post_processing.rs
- examples/3d/3d_gizmos.rs
- examples/animation/cubic_curve.rs
- examples/2d/mesh2d_vertex_color_texture.rs
- examples/transforms/transform.rs
- examples/2d/bloom_2d.rs
- examples/audio/spatial_audio_2d.rs
- examples/audio/spatial_audio_3d.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/3d/spotlight.rs
- examples/2d/sprite_slice.rs
- examples/3d/render_to_texture.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_cubes.rs
- examples/2d/text2d.rs
- examples/games/breakout.rs
- examples/3d/parallax_mapping.rs
pub const fn from_rotation(rotation: Quat) -> Transform
pub const fn from_rotation(rotation: Quat) -> Transform
Creates a new Transform
, with rotation
. Translation will be 0 and scale 1 on
all axes.
Examples found in repository?
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
fn setup(asset_server: Res<AssetServer>, mut commands: Commands) {
commands.insert_resource(MorphData {
the_wave: asset_server.load("models/animated/MorphStressTest.gltf#Animation2"),
mesh: asset_server.load("models/animated/MorphStressTest.gltf#Mesh0/Primitive0"),
});
commands.spawn(SceneBundle {
scene: asset_server.load("models/animated/MorphStressTest.gltf#Scene0"),
..default()
});
commands.spawn(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_rotation_z(PI / 2.0)),
..default()
});
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(3.0, 2.1, 10.2).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
More examples
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Spawn a cube to scale.
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: materials.add(Color::WHITE),
transform: Transform::from_rotation(Quat::from_rotation_y(PI / 4.0)),
..default()
},
Scaling::new(),
));
// Spawn a camera looking at the entities to show what's happening in this example.
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// Add a light source for better 3d visibility.
commands.spawn(DirectionalLightBundle {
transform: Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// circular base
commands.spawn(PbrBundle {
mesh: meshes.add(Circle::new(4.0)),
material: materials.add(Color::WHITE),
transform: Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
..default()
});
// cube
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(Color::rgb_u8(124, 144, 255)),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
// light
commands.spawn(PointLightBundle {
point_light: PointLight {
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0, 8.0, 4.0),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Insert a resource with the current scene information
commands.insert_resource(Animations(vec![
asset_server.load("models/animated/Fox.glb#Animation2"),
asset_server.load("models/animated/Fox.glb#Animation1"),
asset_server.load("models/animated/Fox.glb#Animation0"),
]));
// Camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(100.0, 100.0, 150.0)
.looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
..default()
});
// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0)),
material: materials.add(Color::rgb(0.3, 0.5, 0.3)),
..default()
});
// Light
commands.spawn(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
directional_light: DirectionalLight {
shadows_enabled: true,
..default()
},
cascade_shadow_config: CascadeShadowConfigBuilder {
first_cascade_far_bound: 200.0,
maximum_distance: 400.0,
..default()
}
.into(),
..default()
});
// Fox
commands.spawn(SceneBundle {
scene: asset_server.load("models/animated/Fox.glb#Scene0"),
..default()
});
println!("Animation controls:");
println!(" - spacebar: play / pause");
println!(" - arrow up / down: speed up / slow down animation playback");
println!(" - arrow left / right: seek backward / forward");
println!(" - digit 1 / 3 / 5: play the animation <digit> times");
println!(" - L: loop the animation forever");
println!(" - return: change animation");
}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// load a texture and retrieve its aspect ratio
let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
let aspect = 0.25;
// create a new quad mesh. this is what we will apply the texture to
let quad_width = 8.0;
let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
// this material renders the texture normally
let material_handle = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// this material modulates the texture to make it red (and slightly transparent)
let red_material_handle = materials.add(StandardMaterial {
base_color: Color::rgba(1.0, 0.0, 0.0, 0.5),
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// and lets make this one blue! (and also slightly transparent)
let blue_material_handle = materials.add(StandardMaterial {
base_color: Color::rgba(0.0, 0.0, 1.0, 0.5),
base_color_texture: Some(texture_handle),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// textured quad - normal
commands.spawn(PbrBundle {
mesh: quad_handle.clone(),
material: material_handle,
transform: Transform::from_xyz(0.0, 0.0, 1.5)
.with_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// textured quad - modulated
commands.spawn(PbrBundle {
mesh: quad_handle.clone(),
material: red_material_handle,
transform: Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// textured quad - modulated
commands.spawn(PbrBundle {
mesh: quad_handle,
material: blue_material_handle,
transform: Transform::from_xyz(0.0, 0.0, -1.5)
.with_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
asset_server: Res<AssetServer>,
) {
commands
.spawn(Camera3dBundle {
camera: Camera {
hdr: true,
..default()
},
transform: Transform::from_xyz(-2.0, 2.0, -2.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
})
.insert(ScreenSpaceAmbientOcclusionBundle::default())
.insert(TemporalAntiAliasBundle::default());
let material = materials.add(StandardMaterial {
base_color: Color::rgb(0.5, 0.5, 0.5),
perceptual_roughness: 1.0,
reflectance: 0.0,
..default()
});
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: material.clone(),
transform: Transform::from_xyz(0.0, 0.0, 1.0),
..default()
});
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: material.clone(),
transform: Transform::from_xyz(0.0, -1.0, 0.0),
..default()
});
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::default()),
material,
transform: Transform::from_xyz(1.0, 0.0, 0.0),
..default()
});
commands.spawn((
PbrBundle {
mesh: meshes.add(Sphere::new(0.4).mesh().uv(72, 36)),
material: materials.add(StandardMaterial {
base_color: Color::rgb(0.4, 0.4, 0.4),
perceptual_roughness: 1.0,
reflectance: 0.0,
..default()
}),
..default()
},
SphereMarker,
));
commands.spawn(DirectionalLightBundle {
directional_light: DirectionalLight {
shadows_enabled: true,
..default()
},
transform: Transform::from_rotation(Quat::from_euler(
EulerRot::ZYX,
0.0,
PI * -0.15,
PI * -0.15,
)),
..default()
});
commands.spawn(
TextBundle::from_section(
"",
TextStyle {
font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 26.0,
..default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::Px(10.0),
left: Val::Px(10.0),
..default()
}),
);
}
pub const fn from_scale(scale: Vec3) -> Transform
pub const fn from_scale(scale: Vec3) -> Transform
Creates a new Transform
, with scale
. Translation will be 0 and rotation 0 on
all axes.
Examples found in repository?
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
fn spawn_fox(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(SceneBundle {
scene: assets.fox.clone(),
visibility: Visibility::Hidden,
transform: Transform::from_scale(Vec3::splat(FOX_SCALE)),
..default()
})
.insert(MainObject);
}
fn spawn_text(commands: &mut Commands, app_status: &AppStatus, asset_server: &AssetServer) {
commands.spawn(
TextBundle {
text: app_status.create_text(asset_server),
..TextBundle::default()
}
.with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::Px(10.0),
left: Val::Px(10.0),
..default()
}),
);
}
// A system that updates the help text.
fn update_text(
mut text_query: Query<&mut Text>,
app_status: Res<AppStatus>,
asset_server: Res<AssetServer>,
) {
for mut text in text_query.iter_mut() {
*text = app_status.create_text(&asset_server);
}
}
impl AppStatus {
// Constructs the help text at the bottom of the screen based on the
// application status.
fn create_text(&self, asset_server: &AssetServer) -> Text {
let irradiance_volume_help_text = if self.irradiance_volume_present {
DISABLE_IRRADIANCE_VOLUME_HELP_TEXT
} else {
ENABLE_IRRADIANCE_VOLUME_HELP_TEXT
};
let voxels_help_text = if self.voxels_visible {
HIDE_VOXELS_HELP_TEXT
} else {
SHOW_VOXELS_HELP_TEXT
};
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
let switch_mesh_help_text = match self.model {
ExampleModel::Sphere => SWITCH_TO_FOX_HELP_TEXT,
ExampleModel::Fox => SWITCH_TO_SPHERE_HELP_TEXT,
};
Text::from_section(
format!(
"{}\n{}\n{}\n{}\n{}",
CLICK_TO_MOVE_HELP_TEXT,
voxels_help_text,
irradiance_volume_help_text,
rotation_help_text,
switch_mesh_help_text
),
TextStyle {
font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 24.0,
color: Color::ANTIQUE_WHITE,
},
)
}
}
// Rotates the camera a bit every frame.
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
time: Res<Time>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED * time.delta_seconds())
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
// Toggles between the unskinned sphere model and the skinned fox model if the
// user requests it.
fn change_main_object(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut sphere_query: Query<
&mut Visibility,
(With<MainObject>, With<Handle<Mesh>>, Without<Handle<Scene>>),
>,
mut fox_query: Query<&mut Visibility, (With<MainObject>, With<Handle<Scene>>)>,
) {
if !keyboard.just_pressed(KeyCode::Tab) {
return;
}
let Some(mut sphere_visibility) = sphere_query.iter_mut().next() else {
return;
};
let Some(mut fox_visibility) = fox_query.iter_mut().next() else {
return;
};
match app_status.model {
ExampleModel::Sphere => {
*sphere_visibility = Visibility::Hidden;
*fox_visibility = Visibility::Visible;
app_status.model = ExampleModel::Fox;
}
ExampleModel::Fox => {
*sphere_visibility = Visibility::Visible;
*fox_visibility = Visibility::Hidden;
app_status.model = ExampleModel::Sphere;
}
}
}
impl Default for AppStatus {
fn default() -> Self {
Self {
irradiance_volume_present: true,
rotating: true,
model: ExampleModel::Sphere,
voxels_visible: false,
}
}
}
// Turns on and off the irradiance volume as requested by the user.
fn toggle_irradiance_volumes(
mut commands: Commands,
keyboard: Res<ButtonInput<KeyCode>>,
light_probe_query: Query<Entity, With<LightProbe>>,
mut app_status: ResMut<AppStatus>,
assets: Res<ExampleAssets>,
mut ambient_light: ResMut<AmbientLight>,
) {
if !keyboard.just_pressed(KeyCode::Space) {
return;
};
let Some(light_probe) = light_probe_query.iter().next() else {
return;
};
if app_status.irradiance_volume_present {
commands.entity(light_probe).remove::<IrradianceVolume>();
ambient_light.brightness = AMBIENT_LIGHT_BRIGHTNESS * IRRADIANCE_VOLUME_INTENSITY;
app_status.irradiance_volume_present = false;
} else {
commands.entity(light_probe).insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
});
ambient_light.brightness = 0.0;
app_status.irradiance_volume_present = true;
}
}
fn toggle_rotation(keyboard: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>) {
if keyboard.just_pressed(KeyCode::Enter) {
app_status.rotating = !app_status.rotating;
}
}
// Handles clicks on the plane that reposition the object.
fn handle_mouse_clicks(
buttons: Res<ButtonInput<MouseButton>>,
windows: Query<&Window, With<PrimaryWindow>>,
cameras: Query<(&Camera, &GlobalTransform)>,
mut main_objects: Query<&mut Transform, With<MainObject>>,
) {
if !buttons.pressed(MouseButton::Left) {
return;
}
let Some(mouse_position) = windows
.iter()
.next()
.and_then(|window| window.cursor_position())
else {
return;
};
let Some((camera, camera_transform)) = cameras.iter().next() else {
return;
};
// Figure out where the user clicked on the plane.
let Some(ray) = camera.viewport_to_world(camera_transform, mouse_position) else {
return;
};
let Some(ray_distance) = ray.intersect_plane(Vec3::ZERO, Plane3d::new(Vec3::Y)) else {
return;
};
let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance;
// Move all the main objeccts.
for mut transform in main_objects.iter_mut() {
transform.translation = vec3(
plane_intersection.x,
transform.translation.y,
plane_intersection.z,
);
}
}
impl FromWorld for ExampleAssets {
fn from_world(world: &mut World) -> Self {
// Load all the assets.
let asset_server = world.resource::<AssetServer>();
let fox = asset_server.load("models/animated/Fox.glb#Scene0");
let main_scene =
asset_server.load("models/IrradianceVolumeExample/IrradianceVolumeExample.glb#Scene0");
let irradiance_volume = asset_server.load::<Image>("irradiance_volumes/Example.vxgi.ktx2");
let fox_animation =
asset_server.load::<AnimationClip>("models/animated/Fox.glb#Animation1");
// Just use a specular map for the skybox since it's not too blurry.
// In reality you wouldn't do this--you'd use a real skybox texture--but
// reusing the textures like this saves space in the Bevy repository.
let skybox = asset_server.load::<Image>("environment_maps/pisa_specular_rgb9e5_zstd.ktx2");
let mut mesh_assets = world.resource_mut::<Assets<Mesh>>();
let main_sphere = mesh_assets.add(Sphere::default().mesh().uv(32, 18));
let voxel_cube = mesh_assets.add(Cuboid::default());
let mut standard_material_assets = world.resource_mut::<Assets<StandardMaterial>>();
let main_material = standard_material_assets.add(Color::SILVER);
ExampleAssets {
main_sphere,
fox,
main_sphere_material: main_material,
main_scene,
irradiance_volume,
fox_animation,
voxel_cube,
skybox,
}
}
}
// Plays the animation on the fox.
fn play_animations(assets: Res<ExampleAssets>, mut players: Query<&mut AnimationPlayer>) {
for mut player in players.iter_mut() {
// This will safely do nothing if the animation is already playing.
player.play(assets.fox_animation.clone()).repeat();
}
}
fn create_cubes(
image_assets: Res<Assets<Image>>,
mut commands: Commands,
irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
voxel_cubes: Query<Entity, With<VoxelCube>>,
example_assets: Res<ExampleAssets>,
mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
// If voxel cubes have already been spawned, don't do anything.
if !voxel_cubes.is_empty() {
return;
}
let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
return;
};
for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
continue;
};
let resolution = image.texture_descriptor.size;
let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
base: StandardMaterial::from(Color::RED),
extension: VoxelVisualizationExtension {
irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
transform: VOXEL_TRANSFORM.inverse(),
inverse_transform: VOXEL_TRANSFORM,
resolution: uvec3(
resolution.width,
resolution.height,
resolution.depth_or_array_layers,
),
intensity: IRRADIANCE_VOLUME_INTENSITY,
},
},
});
let scale = vec3(
1.0 / resolution.width as f32,
1.0 / resolution.height as f32,
1.0 / resolution.depth_or_array_layers as f32,
);
// Spawn a cube for each voxel.
for z in 0..resolution.depth_or_array_layers {
for y in 0..resolution.height {
for x in 0..resolution.width {
let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
let pos = global_transform.transform_point(uvw);
let voxel_cube = commands
.spawn(MaterialMeshBundle {
mesh: example_assets.voxel_cube.clone(),
material: voxel_cube_material.clone(),
transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
.with_translation(pos),
..default()
})
.insert(VoxelCube)
.insert(NotShadowCaster)
.id();
commands.entity(voxel_cube_parent).add_child(voxel_cube);
}
}
}
}
}
More examples
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
fn spawn_system(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
let texture = asset_server.load("branding/icon.png");
let mut rng = StdRng::seed_from_u64(19878367467713);
for _ in 0..128 {
commands.spawn((
SpriteBundle {
texture: texture.clone(),
transform: Transform::from_scale(Vec3::splat(0.1)),
..default()
},
Velocity(20.0 * Vec2::new(rng.gen::<f32>() - 0.5, rng.gen::<f32>() - 0.5)),
));
}
}
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<CustomMaterial>>,
) {
// Add a mesh loaded from a glTF file. This mesh has data for `ATTRIBUTE_BARYCENTRIC`.
let mesh = asset_server.load("models/barycentric/barycentric.gltf#Mesh0/Primitive0");
commands.spawn(MaterialMesh2dBundle {
mesh: Mesh2dHandle(mesh),
material: materials.add(CustomMaterial {}),
transform: Transform::from_scale(150.0 * Vec3::ONE),
..default()
});
// Add a camera
commands.spawn(Camera2dBundle { ..default() });
}
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
fn spawn_reflection_probe(commands: &mut Commands, cubemaps: &Cubemaps) {
commands.spawn(ReflectionProbeBundle {
spatial: SpatialBundle {
// 2.0 because the sphere's radius is 1.0 and we want to fully enclose it.
transform: Transform::from_scale(Vec3::splat(2.0)),
..SpatialBundle::default()
},
light_probe: LightProbe,
environment_map: EnvironmentMapLight {
diffuse_map: cubemaps.diffuse.clone(),
specular_map: cubemaps.specular_reflection_probe.clone(),
intensity: 5000.0,
},
});
}
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
let texture = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
let layout = TextureAtlasLayout::from_grid(Vec2::new(24.0, 24.0), 7, 1, None, None);
let texture_atlas_layout = texture_atlas_layouts.add(layout);
// Use only the subset of sprites in the sheet that make up the run animation
let animation_indices = AnimationIndices { first: 1, last: 6 };
commands.spawn(Camera2dBundle::default());
commands.spawn((
SpriteSheetBundle {
texture,
atlas: TextureAtlas {
layout: texture_atlas_layout,
index: animation_indices.first,
},
transform: Transform::from_scale(Vec3::splat(6.0)),
..default()
},
animation_indices,
AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)),
));
}
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
fn setup_terrain_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
asset_server: Res<AssetServer>,
) {
// Configure a properly scaled cascade shadow map for this scene (defaults are too large, mesh units are in km)
let cascade_shadow_config = CascadeShadowConfigBuilder {
first_cascade_far_bound: 0.3,
maximum_distance: 3.0,
..default()
}
.build();
// Sun
commands.spawn(DirectionalLightBundle {
directional_light: DirectionalLight {
color: Color::rgb(0.98, 0.95, 0.82),
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(0.0, 0.0, 0.0)
.looking_at(Vec3::new(-0.15, -0.05, 0.25), Vec3::Y),
cascade_shadow_config,
..default()
});
// Terrain
commands.spawn(SceneBundle {
scene: asset_server.load("models/terrain/Mountains.gltf#Scene0"),
..default()
});
// Sky
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::new(2.0, 1.0, 1.0)),
material: materials.add(StandardMaterial {
base_color: Color::hex("888888").unwrap(),
unlit: true,
cull_mode: None,
..default()
}),
transform: Transform::from_scale(Vec3::splat(20.0)),
..default()
},
NotShadowCaster,
));
}
pub fn looking_at(self, target: Vec3, up: Vec3) -> Transform
pub fn looking_at(self, target: Vec3, up: Vec3) -> Transform
Returns this Transform
with a new rotation so that Transform::forward
points towards the target
position and Transform::up
points towards up
.
In some cases it’s not possible to construct a rotation. Another axis will be picked in those cases:
- if
target
is the same as the transform translation,Vec3::Z
is used instead - if
up
is zero,Vec3::Y
is used instead - if the resulting forward direction is parallel with
up
, an orthogonal vector is used as the “right” direction
Examples found in repository?
More examples
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
fn setup(mut commands: Commands) {
warn!(include_str!("warning_string.txt"));
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(3., 1., 5.).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
commands.spawn(TextBundle::from_section(
"",
TextStyle {
font_size: 30.,
..default()
},
));
}
20 21 22 23 24 25 26 27 28 29 30 31 32
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Create a camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// Spawn the first scene in `models/SimpleSkin/SimpleSkin.gltf`
commands.spawn(SceneBundle {
scene: asset_server.load("models/SimpleSkin/SimpleSkin.gltf#Scene0"),
..default()
});
}
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
game.camera_is_focus = game.camera_should_focus;
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(
-(BOARD_SIZE_I as f32 / 2.0),
2.0 * BOARD_SIZE_J as f32 / 3.0,
BOARD_SIZE_J as f32 / 2.0 - 0.5,
)
.looking_at(game.camera_is_focus, Vec3::Y),
..default()
});
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
// reset the game state
game.cake_eaten = 0;
game.score = 0;
game.player.i = BOARD_SIZE_I / 2;
game.player.j = BOARD_SIZE_J / 2;
game.player.move_cooldown = Timer::from_seconds(0.3, TimerMode::Once);
commands.spawn(PointLightBundle {
transform: Transform::from_xyz(4.0, 10.0, 4.0),
point_light: PointLight {
intensity: 2_000_000.0,
shadows_enabled: true,
range: 30.0,
..default()
},
..default()
});
// spawn the game board
let cell_scene = asset_server.load("models/AlienCake/tile.glb#Scene0");
game.board = (0..BOARD_SIZE_J)
.map(|j| {
(0..BOARD_SIZE_I)
.map(|i| {
let height = rand::thread_rng().gen_range(-0.1..0.1);
commands.spawn(SceneBundle {
transform: Transform::from_xyz(i as f32, height - 0.2, j as f32),
scene: cell_scene.clone(),
..default()
});
Cell { height }
})
.collect()
})
.collect();
// spawn the game character
game.player.entity = Some(
commands
.spawn(SceneBundle {
transform: Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(-PI / 2.),
..default()
},
scene: asset_server.load("models/AlienCake/alien.glb#Scene0"),
..default()
})
.id(),
);
// load the scene for the cake
game.bonus.handle = asset_server.load("models/AlienCake/cakeBirthday.glb#Scene0");
// scoreboard
commands.spawn(
TextBundle::from_section(
"Score:",
TextStyle {
font_size: 40.0,
color: Color::rgb(0.5, 0.5, 1.0),
..default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(5.0),
left: Val::Px(5.0),
..default()
}),
);
}
// remove all entities that are not a camera or window
fn teardown(mut commands: Commands, entities: Query<Entity, (Without<Camera>, Without<Window>)>) {
for entity in &entities {
commands.entity(entity).despawn();
}
}
// control the game character
fn move_player(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut game: ResMut<Game>,
mut transforms: Query<&mut Transform>,
time: Res<Time>,
) {
if game.player.move_cooldown.tick(time.delta()).finished() {
let mut moved = false;
let mut rotation = 0.0;
if keyboard_input.pressed(KeyCode::ArrowUp) {
if game.player.i < BOARD_SIZE_I - 1 {
game.player.i += 1;
}
rotation = -PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
if game.player.i > 0 {
game.player.i -= 1;
}
rotation = PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
if game.player.j < BOARD_SIZE_J - 1 {
game.player.j += 1;
}
rotation = PI;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
if game.player.j > 0 {
game.player.j -= 1;
}
rotation = 0.0;
moved = true;
}
// move on the board
if moved {
game.player.move_cooldown.reset();
*transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(rotation),
..default()
};
}
}
// eat the cake!
if let Some(entity) = game.bonus.entity {
if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
game.score += 2;
game.cake_eaten += 1;
commands.entity(entity).despawn_recursive();
game.bonus.entity = None;
}
}
}
// change the focus of the camera
fn focus_camera(
time: Res<Time>,
mut game: ResMut<Game>,
mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
) {
const SPEED: f32 = 2.0;
// if there is both a player and a bonus, target the mid-point of them
if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
let transform_query = transforms.p1();
if let (Ok(player_transform), Ok(bonus_transform)) = (
transform_query.get(player_entity),
transform_query.get(bonus_entity),
) {
game.camera_should_focus = player_transform
.translation
.lerp(bonus_transform.translation, 0.5);
}
// otherwise, if there is only a player, target the player
} else if let Some(player_entity) = game.player.entity {
if let Ok(player_transform) = transforms.p1().get(player_entity) {
game.camera_should_focus = player_transform.translation;
}
// otherwise, target the middle
} else {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
}
// calculate the camera motion based on the difference between where the camera is looking
// and where it should be looking; the greater the distance, the faster the motion;
// smooth out the camera movement using the frame time
let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
if camera_motion.length() > 0.2 {
camera_motion *= SPEED * time.delta_seconds();
// set the new camera's actual focus
game.camera_is_focus += camera_motion;
}
// look at that new camera's actual focus
for mut transform in transforms.p0().iter_mut() {
*transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
}
}
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
fn setup_cameras(mut commands: Commands) {
let start_in_2d = true;
let make_camera = |is_active| Camera {
is_active,
..Default::default()
};
commands.spawn(Camera2dBundle {
camera: make_camera(start_in_2d),
..Default::default()
});
commands.spawn(Camera3dBundle {
camera: make_camera(!start_in_2d),
transform: Transform::from_xyz(0.0, 10.0, 0.0).looking_at(Vec3::ZERO, Vec3::Z),
..Default::default()
});
}
fn setup_ambient_light(mut ambient_light: ResMut<AmbientLight>) {
ambient_light.brightness = 50.0;
}
fn setup_lights(mut commands: Commands) {
commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 5000.0,
..default()
},
transform: Transform::from_translation(Vec3::new(-LEFT_RIGHT_OFFSET_3D, 2.0, 0.0))
.looking_at(Vec3::new(-LEFT_RIGHT_OFFSET_3D, 0.0, 0.0), Vec3::Y),
..default()
});
}
- examples/shader/animate_shader.rs
- examples/async_tasks/async_compute.rs
- examples/shader/array_texture.rs
- examples/shader/fallback_image.rs
- examples/shader/shader_material.rs
- examples/3d/3d_viewport_to_world.rs
- examples/animation/morph_targets.rs
- examples/shader/texture_binding_array.rs
- examples/shader/custom_vertex_attribute.rs
- examples/transforms/3d_rotation.rs
- examples/3d/atmospheric_fog.rs
- examples/transforms/scale.rs
- examples/transforms/translation.rs
- examples/shader/shader_defs.rs
- tests/window/minimising.rs
- tests/window/resizing.rs
- examples/3d/tonemapping.rs
- examples/3d/animated_material.rs
- examples/3d/3d_scene.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/shader/post_processing.rs
- examples/3d/skybox.rs
- examples/3d/parenting.rs
- examples/3d/lines.rs
- examples/3d/load_gltf.rs
- examples/3d/two_passes.rs
- examples/3d/update_gltf_scene.rs
- examples/shader/shader_instancing.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/animation/cubic_curve.rs
- examples/shader/extended_material.rs
- examples/3d/vertex_colors.rs
- examples/3d/orthographic.rs
- examples/3d/generate_custom_mesh.rs
- examples/window/multiple_windows.rs
- examples/3d/3d_shapes.rs
- examples/transforms/transform.rs
- examples/3d/spherical_area_lights.rs
- examples/animation/animated_fox.rs
- examples/3d/3d_gizmos.rs
- examples/3d/wireframe.rs
- examples/window/low_power.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/texture.rs
- examples/3d/ssao.rs
- examples/3d/bloom_3d.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/transparency_3d.rs
- examples/ecs/iter_combinations.rs
- examples/3d/anti_aliasing.rs
- examples/ui/render_ui_to_texture.rs
- examples/3d/spotlight.rs
- examples/asset/asset_loading.rs
- examples/3d/pbr.rs
- examples/3d/render_to_texture.rs
- examples/stress_tests/many_foxes.rs
- examples/shader/shader_prepass.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/fog.rs
- examples/3d/parallax_mapping.rs
- examples/3d/split_screen.rs
- examples/animation/animated_transform.rs
- examples/3d/shadow_biases.rs
- examples/3d/deferred_rendering.rs
- examples/3d/blend_modes.rs
- examples/3d/lighting.rs
- examples/3d/transmission.rs
pub fn looking_to(self, direction: Vec3, up: Vec3) -> Transform
pub fn looking_to(self, direction: Vec3, up: Vec3) -> Transform
Returns this Transform
with a new rotation so that Transform::forward
points in the given direction
and Transform::up
points towards up
.
In some cases it’s not possible to construct a rotation. Another axis will be picked in those cases:
- if
direction
is zero,Vec3::Z
is used instead - if
up
is zero,Vec3::Y
is used instead - if
direction
is parallel withup
, an orthogonal vector is used as the “right” direction
pub const fn with_translation(self, translation: Vec3) -> Transform
pub const fn with_translation(self, translation: Vec3) -> Transform
Returns this Transform
with a new translation.
Examples found in repository?
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
fn setup_pyramid_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let stone = materials.add(StandardMaterial {
base_color: Color::hex("28221B").unwrap(),
perceptual_roughness: 1.0,
..default()
});
// pillars
for (x, z) in &[(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5)] {
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 3.0, 1.0)),
material: stone.clone(),
transform: Transform::from_xyz(*x, 1.5, *z),
..default()
});
}
// orb
commands.spawn((
PbrBundle {
mesh: meshes.add(Sphere::default()),
material: materials.add(StandardMaterial {
base_color: Color::hex("126212CC").unwrap(),
reflectance: 1.0,
perceptual_roughness: 0.0,
metallic: 0.5,
alpha_mode: AlphaMode::Blend,
..default()
}),
transform: Transform::from_scale(Vec3::splat(1.75))
.with_translation(Vec3::new(0.0, 4.0, 0.0)),
..default()
},
NotShadowCaster,
NotShadowReceiver,
));
// steps
for i in 0..50 {
let half_size = i as f32 / 2.0 + 3.0;
let y = -i as f32 / 2.0;
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(2.0 * half_size, 0.5, 2.0 * half_size)),
material: stone.clone(),
transform: Transform::from_xyz(0.0, y + 0.25, 0.0),
..default()
});
}
// sky
commands.spawn(PbrBundle {
mesh: meshes.add(Cuboid::new(2.0, 1.0, 1.0)),
material: materials.add(StandardMaterial {
base_color: Color::hex("888888").unwrap(),
unlit: true,
cull_mode: None,
..default()
}),
transform: Transform::from_scale(Vec3::splat(1_000_000.0)),
..default()
});
// light
commands.spawn(PointLightBundle {
transform: Transform::from_xyz(0.0, 1.0, 0.0),
point_light: PointLight {
shadows_enabled: true,
..default()
},
..default()
});
}
More examples
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
fn create_cubes(
image_assets: Res<Assets<Image>>,
mut commands: Commands,
irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
voxel_cubes: Query<Entity, With<VoxelCube>>,
example_assets: Res<ExampleAssets>,
mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
// If voxel cubes have already been spawned, don't do anything.
if !voxel_cubes.is_empty() {
return;
}
let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
return;
};
for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
continue;
};
let resolution = image.texture_descriptor.size;
let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
base: StandardMaterial::from(Color::RED),
extension: VoxelVisualizationExtension {
irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
transform: VOXEL_TRANSFORM.inverse(),
inverse_transform: VOXEL_TRANSFORM,
resolution: uvec3(
resolution.width,
resolution.height,
resolution.depth_or_array_layers,
),
intensity: IRRADIANCE_VOLUME_INTENSITY,
},
},
});
let scale = vec3(
1.0 / resolution.width as f32,
1.0 / resolution.height as f32,
1.0 / resolution.depth_or_array_layers as f32,
);
// Spawn a cube for each voxel.
for z in 0..resolution.depth_or_array_layers {
for y in 0..resolution.height {
for x in 0..resolution.width {
let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
let pos = global_transform.transform_point(uvw);
let voxel_cube = commands
.spawn(MaterialMeshBundle {
mesh: example_assets.voxel_cube.clone(),
material: voxel_cube_material.clone(),
transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
.with_translation(pos),
..default()
})
.insert(VoxelCube)
.insert(NotShadowCaster)
.id();
commands.entity(voxel_cube_parent).add_child(voxel_cube);
}
}
}
}
}
pub const fn with_rotation(self, rotation: Quat) -> Transform
pub const fn with_rotation(self, rotation: Quat) -> Transform
Returns this Transform
with a new rotation.
Examples found in repository?
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// directional 'sun' light
commands.spawn(DirectionalLightBundle {
directional_light: DirectionalLight {
illuminance: 32000.0,
..default()
},
transform: Transform::from_xyz(0.0, 2.0, 0.0)
.with_rotation(Quat::from_rotation_x(-PI / 4.)),
..default()
});
let skybox_handle = asset_server.load(CUBEMAPS[0].0);
// camera
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
},
CameraController::default(),
Skybox {
image: skybox_handle.clone(),
brightness: 150.0,
},
));
// ambient light
// NOTE: The ambient light is used to scale how bright the environment map is so with a bright
// environment map, use an appropriate color and brightness to match
commands.insert_resource(AmbientLight {
color: Color::rgb_u8(210, 220, 240),
brightness: 1.0,
});
commands.insert_resource(Cubemap {
is_loaded: false,
index: 0,
image_handle: skybox_handle,
});
}
More examples
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut images: ResMut<Assets<Image>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let debug_material = materials.add(StandardMaterial {
base_color_texture: Some(images.add(uv_debug_texture())),
..default()
});
let shapes = [
meshes.add(Cuboid::default()),
meshes.add(Capsule3d::default()),
meshes.add(Torus::default()),
meshes.add(Cylinder::default()),
meshes.add(Sphere::default().mesh().ico(5).unwrap()),
meshes.add(Sphere::default().mesh().uv(32, 18)),
];
let num_shapes = shapes.len();
for (i, shape) in shapes.into_iter().enumerate() {
commands.spawn((
PbrBundle {
mesh: shape,
material: debug_material.clone(),
transform: Transform::from_xyz(
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
2.0,
0.0,
)
.with_rotation(Quat::from_rotation_x(-PI / 4.)),
..default()
},
Shape,
));
}
commands.spawn(PointLightBundle {
point_light: PointLight {
shadows_enabled: true,
intensity: 10_000_000.,
range: 100.0,
..default()
},
transform: Transform::from_xyz(8.0, 16.0, 8.0),
..default()
});
// ground plane
commands.spawn(PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(50.0, 50.0)),
material: materials.add(Color::SILVER),
..default()
});
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 6., 12.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
..default()
});
}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Add an object (sphere) for visualizing scaling.
commands.spawn((
PbrBundle {
mesh: meshes.add(Sphere::new(3.0).mesh().ico(32).unwrap()),
material: materials.add(Color::YELLOW),
transform: Transform::from_translation(Vec3::ZERO),
..default()
},
Center {
max_size: 1.0,
min_size: 0.1,
scale_factor: 0.05,
},
));
// Add the cube to visualize rotation and translation.
// This cube will circle around the center_sphere
// by changing its rotation each frame and moving forward.
// Define a start transform for an orbiting cube, that's away from our central object (sphere)
// and rotate it so it will be able to move around the sphere and not towards it.
let cube_spawn =
Transform::from_translation(Vec3::Z * -10.0).with_rotation(Quat::from_rotation_y(PI / 2.));
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::default()),
material: materials.add(Color::WHITE),
transform: cube_spawn,
..default()
},
CubeState {
start_pos: cube_spawn.translation,
move_speed: 2.0,
turn_speed: 0.2,
},
));
// Spawn a camera looking at the entities to show what's happening in this example.
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
// Add a light source for better 3d visibility.
commands.spawn(DirectionalLightBundle {
transform: Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// load a texture and retrieve its aspect ratio
let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
let aspect = 0.25;
// create a new quad mesh. this is what we will apply the texture to
let quad_width = 8.0;
let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
// this material renders the texture normally
let material_handle = materials.add(StandardMaterial {
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// this material modulates the texture to make it red (and slightly transparent)
let red_material_handle = materials.add(StandardMaterial {
base_color: Color::rgba(1.0, 0.0, 0.0, 0.5),
base_color_texture: Some(texture_handle.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// and lets make this one blue! (and also slightly transparent)
let blue_material_handle = materials.add(StandardMaterial {
base_color: Color::rgba(0.0, 0.0, 1.0, 0.5),
base_color_texture: Some(texture_handle),
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
// textured quad - normal
commands.spawn(PbrBundle {
mesh: quad_handle.clone(),
material: material_handle,
transform: Transform::from_xyz(0.0, 0.0, 1.5)
.with_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// textured quad - modulated
commands.spawn(PbrBundle {
mesh: quad_handle.clone(),
material: red_material_handle,
transform: Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// textured quad - modulated
commands.spawn(PbrBundle {
mesh: quad_handle,
material: blue_material_handle,
transform: Transform::from_xyz(0.0, 0.0, -1.5)
.with_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
});
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut images: ResMut<Assets<Image>>,
) {
let size = Extent3d {
width: 512,
height: 512,
..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,
view_formats: &[],
},
..default()
};
// fill image.data with zeroes
image.resize(size);
let image_handle = images.add(image);
// Light
commands.spawn(DirectionalLightBundle::default());
let texture_camera = commands
.spawn(Camera2dBundle {
camera: Camera {
// render before the "main pass" camera
order: -1,
target: RenderTarget::Image(image_handle.clone()),
..default()
},
..default()
})
.id();
commands
.spawn((
NodeBundle {
style: Style {
// Cover the whole image
width: Val::Percent(100.),
height: Val::Percent(100.),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
background_color: Color::GOLD.into(),
..default()
},
TargetCamera(texture_camera),
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"This is a cube",
TextStyle {
font_size: 40.0,
color: Color::BLACK,
..default()
},
));
});
let cube_size = 4.0;
let cube_handle = meshes.add(Cuboid::new(cube_size, cube_size, cube_size));
// This material has the texture that has been rendered.
let material_handle = materials.add(StandardMaterial {
base_color_texture: Some(image_handle),
reflectance: 0.02,
unlit: false,
..default()
});
// Cube with material containing the rendered UI texture.
commands.spawn((
PbrBundle {
mesh: cube_handle,
material: material_handle,
transform: Transform::from_xyz(0.0, 0.0, 1.5)
.with_rotation(Quat::from_rotation_x(-PI / 5.0)),
..default()
},
Cube,
));
// The main pass camera.
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
}
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
fn setup_basic_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut images: ResMut<Assets<Image>>,
asset_server: Res<AssetServer>,
) {
// plane
commands.spawn((
PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(50.0, 50.0)),
material: materials.add(Color::rgb(0.1, 0.2, 0.1)),
..default()
},
SceneNumber(1),
));
// cubes
let cube_material = materials.add(StandardMaterial {
base_color_texture: Some(images.add(uv_debug_texture())),
..default()
});
let cube_mesh = meshes.add(Cuboid::new(0.25, 0.25, 0.25));
for i in 0..5 {
commands.spawn((
PbrBundle {
mesh: cube_mesh.clone(),
material: cube_material.clone(),
transform: Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
..default()
},
SceneNumber(1),
));
}
// spheres
let sphere_mesh = meshes.add(Sphere::new(0.125).mesh().uv(32, 18));
for i in 0..6 {
let j = i % 3;
let s_val = if i < 3 { 0.0 } else { 0.2 };
let material = if j == 0 {
materials.add(StandardMaterial {
base_color: Color::rgb(s_val, s_val, 1.0),
perceptual_roughness: 0.089,
metallic: 0.0,
..default()
})
} else if j == 1 {
materials.add(StandardMaterial {
base_color: Color::rgb(s_val, 1.0, s_val),
perceptual_roughness: 0.089,
metallic: 0.0,
..default()
})
} else {
materials.add(StandardMaterial {
base_color: Color::rgb(1.0, s_val, s_val),
perceptual_roughness: 0.089,
metallic: 0.0,
..default()
})
};
commands.spawn((
PbrBundle {
mesh: sphere_mesh.clone(),
material,
transform: Transform::from_xyz(
j as f32 * 0.25 + if i < 3 { -0.15 } else { 0.15 } - 0.4,
0.125,
-j as f32 * 0.25 + if i < 3 { -0.15 } else { 0.15 } + 0.4,
),
..default()
},
SceneNumber(1),
));
}
// Flight Helmet
commands.spawn((
SceneBundle {
scene: asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0"),
transform: Transform::from_xyz(0.5, 0.0, -0.5)
.with_rotation(Quat::from_rotation_y(-0.15 * PI)),
..default()
},
SceneNumber(1),
));
// light
commands.spawn((
DirectionalLightBundle {
directional_light: DirectionalLight {
illuminance: 15_000.,
shadows_enabled: true,
..default()
},
transform: Transform::from_rotation(Quat::from_euler(
EulerRot::ZYX,
0.0,
PI * -0.15,
PI * -0.15,
)),
cascade_shadow_config: CascadeShadowConfigBuilder {
maximum_distance: 3.0,
first_cascade_far_bound: 0.9,
..default()
}
.into(),
..default()
},
SceneNumber(1),
));
}
pub const fn with_scale(self, scale: Vec3) -> Transform
pub const fn with_scale(self, scale: Vec3) -> Transform
Returns this Transform
with a new scale.
Examples found in repository?
More examples
14 15 16 17 18 19 20 21 22 23 24 25 26
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn(Camera2dBundle::default());
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(Rectangle::default()).into(),
transform: Transform::default().with_scale(Vec3::splat(128.)),
material: materials.add(Color::PURPLE),
..default()
});
}
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
fn setup_mesh(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn((
MaterialMesh2dBundle {
mesh: meshes.add(Capsule2d::default()).into(),
transform: Transform::from_xyz(40., 0., 2.).with_scale(Vec3::splat(32.)),
material: materials.add(Color::BLACK),
..default()
},
Rotate,
PIXEL_PERFECT_LAYERS,
));
}
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<CustomMaterial>>,
asset_server: Res<AssetServer>,
) {
// camera
commands.spawn(Camera2dBundle::default());
// quad
commands.spawn(MaterialMesh2dBundle {
mesh: meshes.add(Rectangle::default()).into(),
transform: Transform::default().with_scale(Vec3::splat(128.)),
material: materials.add(CustomMaterial {
color: Color::BLUE,
color_texture: Some(asset_server.load("branding/icon.png")),
}),
..default()
});
}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
fn bird_velocity_transform(
half_extents: Vec2,
mut translation: Vec3,
velocity_rng: &mut StdRng,
waves: Option<usize>,
dt: f32,
) -> (Transform, Vec3) {
let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);
if let Some(waves) = waves {
// Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
// and with dt-spaced frames of simulation
for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
step_movement(&mut translation, &mut velocity, dt);
handle_collision(half_extents, &translation, &mut velocity);
}
}
(
Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
velocity,
)
}
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
fn draw_example_collection(
mut gizmos: Gizmos,
mut my_gizmos: Gizmos<MyRoundGizmos>,
time: Res<Time>,
) {
gizmos.cuboid(
Transform::from_translation(Vec3::Y * 0.5).with_scale(Vec3::splat(1.25)),
Color::BLACK,
);
gizmos.rect(
Vec3::new(time.elapsed_seconds().cos() * 2.5, 1., 0.),
Quat::from_rotation_y(PI / 2.),
Vec2::splat(2.),
Color::GREEN,
);
my_gizmos.sphere(Vec3::new(1., 0.5, 0.), Quat::IDENTITY, 0.5, Color::RED);
for y in [0., 0.5, 1.] {
gizmos.ray(
Vec3::new(1., y, 0.),
Vec3::new(-3., (time.elapsed_seconds() * 3.).sin(), 0.),
Color::BLUE,
);
}
my_gizmos
.arc_3d(
180.0_f32.to_radians(),
0.2,
Vec3::ONE,
Quat::from_rotation_arc(Vec3::Y, Vec3::ONE.normalize()),
Color::ORANGE,
)
.segments(10);
// Circles have 32 line-segments by default.
my_gizmos.circle(Vec3::ZERO, Direction3d::Y, 3., Color::BLACK);
// You may want to increase this for larger circles or spheres.
my_gizmos
.circle(Vec3::ZERO, Direction3d::Y, 3.1, Color::NAVY)
.segments(64);
my_gizmos
.sphere(Vec3::ZERO, Quat::IDENTITY, 3.2, Color::BLACK)
.circle_segments(64);
gizmos.arrow(Vec3::ZERO, Vec3::ONE * 1.5, Color::YELLOW);
}
pub fn compute_matrix(&self) -> Mat4
pub fn compute_matrix(&self) -> Mat4
Returns the 3d affine transformation matrix from this transforms translation, rotation, and scale.
pub fn compute_affine(&self) -> Affine3A
pub fn compute_affine(&self) -> Affine3A
Returns the 3d affine transformation matrix from this transforms translation, rotation, and scale.
pub fn local_x(&self) -> Direction3d
pub fn local_x(&self) -> Direction3d
Get the unit vector in the local X
direction.
pub fn left(&self) -> Direction3d
pub fn left(&self) -> Direction3d
Equivalent to -local_x()
pub fn right(&self) -> Direction3d
pub fn right(&self) -> Direction3d
Equivalent to local_x()
Examples found in repository?
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
fn run_camera_controller(
time: Res<Time>,
mut windows: Query<&mut Window>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut toggle_cursor_grab: Local<bool>,
mut mouse_cursor_grab: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut controller)) = query.get_single_mut() {
if !controller.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
controller.yaw = yaw;
controller.pitch = pitch;
controller.initialized = true;
info!("{}", *controller);
}
if !controller.enabled {
mouse_events.clear();
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(controller.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(controller.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(controller.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(controller.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(controller.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(controller.key_down) {
axis_input.y -= 1.0;
}
let mut cursor_grab_change = false;
if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
*toggle_cursor_grab = !*toggle_cursor_grab;
cursor_grab_change = true;
}
if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = true;
cursor_grab_change = true;
}
if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = false;
cursor_grab_change = true;
}
let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(controller.key_run) {
controller.run_speed
} else {
controller.walk_speed
};
controller.velocity = axis_input.normalize() * max_speed;
} else {
let friction = controller.friction.clamp(0.0, 1.0);
controller.velocity *= 1.0 - friction;
if controller.velocity.length_squared() < 1e-6 {
controller.velocity = Vec3::ZERO;
}
}
let forward = *transform.forward();
let right = *transform.right();
transform.translation += controller.velocity.x * dt * right
+ controller.velocity.y * dt * Vec3::Y
+ controller.velocity.z * dt * forward;
// Handle cursor grab
if cursor_grab_change {
if cursor_grab {
for mut window in &mut windows {
if !window.focused {
continue;
}
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
} else {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
}
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if cursor_grab {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
} else {
mouse_events.clear();
}
if mouse_delta != Vec2::ZERO {
// Apply look update
controller.pitch = (controller.pitch
- mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
.clamp(-PI / 2., PI / 2.);
controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
transform.rotation =
Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
}
}
}
pub fn local_y(&self) -> Direction3d
pub fn local_y(&self) -> Direction3d
Get the unit vector in the local Y
direction.
Examples found in repository?
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
fn rotate_cube(
mut cubes: Query<(&mut Transform, &mut CubeState), Without<Center>>,
center_spheres: Query<&Transform, With<Center>>,
timer: Res<Time>,
) {
// Calculate the point to circle around. (The position of the center_sphere)
let mut center: Vec3 = Vec3::ZERO;
for sphere in ¢er_spheres {
center += sphere.translation;
}
// Update the rotation of the cube(s).
for (mut transform, cube) in &mut cubes {
// Calculate the rotation of the cube if it would be looking at the sphere in the center.
let look_at_sphere = transform.looking_at(center, *transform.local_y());
// Interpolate between the current rotation and the fully turned rotation
// when looking a the sphere, with a given turn speed to get a smooth motion.
// With higher speed the curvature of the orbit would be smaller.
let incremental_turn_weight = cube.turn_speed * timer.delta_seconds();
let old_rotation = transform.rotation;
transform.rotation = old_rotation.lerp(look_at_sphere.rotation, incremental_turn_weight);
}
}
pub fn up(&self) -> Direction3d
pub fn up(&self) -> Direction3d
Equivalent to local_y()
pub fn down(&self) -> Direction3d
pub fn down(&self) -> Direction3d
Equivalent to -local_y()
pub fn local_z(&self) -> Direction3d
pub fn local_z(&self) -> Direction3d
Get the unit vector in the local Z
direction.
pub fn forward(&self) -> Direction3d
pub fn forward(&self) -> Direction3d
Equivalent to -local_z()
Examples found in repository?
More examples
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
fn setup_color_gradient_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorGradientMaterial>>,
camera_transform: Res<CameraTransform>,
) {
let mut transform = camera_transform.0;
transform.translation += *transform.forward();
commands.spawn((
MaterialMeshBundle {
mesh: meshes.add(Rectangle::new(0.7, 0.7)),
material: materials.add(ColorGradientMaterial {}),
transform,
visibility: Visibility::Hidden,
..default()
},
SceneNumber(2),
));
}
fn setup_image_viewer_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
camera_transform: Res<CameraTransform>,
) {
let mut transform = camera_transform.0;
transform.translation += *transform.forward();
// exr/hdr viewer (exr requires enabling bevy feature)
commands.spawn((
PbrBundle {
mesh: meshes.add(Rectangle::default()),
material: materials.add(StandardMaterial {
base_color_texture: None,
unlit: true,
..default()
}),
transform,
visibility: Visibility::Hidden,
..default()
},
SceneNumber(3),
HDRViewer,
));
commands
.spawn((
TextBundle::from_section(
"Drag and drop an HDR or EXR file",
TextStyle {
font_size: 36.0,
color: Color::BLACK,
..default()
},
)
.with_text_justify(JustifyText::Center)
.with_style(Style {
align_self: AlignSelf::Center,
margin: UiRect::all(Val::Auto),
..default()
}),
SceneNumber(3),
))
.insert(Visibility::Hidden);
}
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
fn run_camera_controller(
time: Res<Time>,
mut windows: Query<&mut Window>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut toggle_cursor_grab: Local<bool>,
mut mouse_cursor_grab: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut controller)) = query.get_single_mut() {
if !controller.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
controller.yaw = yaw;
controller.pitch = pitch;
controller.initialized = true;
info!("{}", *controller);
}
if !controller.enabled {
mouse_events.clear();
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(controller.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(controller.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(controller.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(controller.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(controller.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(controller.key_down) {
axis_input.y -= 1.0;
}
let mut cursor_grab_change = false;
if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
*toggle_cursor_grab = !*toggle_cursor_grab;
cursor_grab_change = true;
}
if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = true;
cursor_grab_change = true;
}
if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = false;
cursor_grab_change = true;
}
let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(controller.key_run) {
controller.run_speed
} else {
controller.walk_speed
};
controller.velocity = axis_input.normalize() * max_speed;
} else {
let friction = controller.friction.clamp(0.0, 1.0);
controller.velocity *= 1.0 - friction;
if controller.velocity.length_squared() < 1e-6 {
controller.velocity = Vec3::ZERO;
}
}
let forward = *transform.forward();
let right = *transform.right();
transform.translation += controller.velocity.x * dt * right
+ controller.velocity.y * dt * Vec3::Y
+ controller.velocity.z * dt * forward;
// Handle cursor grab
if cursor_grab_change {
if cursor_grab {
for mut window in &mut windows {
if !window.focused {
continue;
}
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
} else {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
}
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if cursor_grab {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
} else {
mouse_events.clear();
}
if mouse_delta != Vec2::ZERO {
// Apply look update
controller.pitch = (controller.pitch
- mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
.clamp(-PI / 2., PI / 2.);
controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
transform.rotation =
Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
}
}
}
pub fn back(&self) -> Direction3d
pub fn back(&self) -> Direction3d
Equivalent to local_z()
pub fn rotate(&mut self, rotation: Quat)
pub fn rotate(&mut self, rotation: Quat)
Rotates this Transform
by the given rotation.
If this Transform
has a parent, the rotation
is relative to the rotation of the parent.
§Examples
Examples found in repository?
More examples
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
fn flicker_system(
mut flame: Query<&mut Transform, (With<Flicker>, With<Handle<Mesh>>)>,
mut light: Query<(&mut PointLight, &mut Transform), (With<Flicker>, Without<Handle<Mesh>>)>,
time: Res<Time>,
) {
let s = time.elapsed_seconds();
let a = (s * 6.0).cos() * 0.0125 + (s * 4.0).cos() * 0.025;
let b = (s * 5.0).cos() * 0.0125 + (s * 3.0).cos() * 0.025;
let c = (s * 7.0).cos() * 0.0125 + (s * 2.0).cos() * 0.025;
let (mut light, mut light_transform) = light.single_mut();
let mut flame_transform = flame.single_mut();
light.intensity = 4_000.0 + 3000.0 * (a + b + c);
flame_transform.translation = Vec3::new(-1.0, 1.23, 0.0);
flame_transform.look_at(Vec3::new(-1.0 - c, 1.7 - b, 0.0 - a), Vec3::X);
flame_transform.rotate(Quat::from_euler(EulerRot::XYZ, 0.0, 0.0, PI / 2.0));
light_transform.translation = Vec3::new(-1.0 - c, 1.7, 0.0 - a);
flame_transform.translation = Vec3::new(-1.0 - c, 1.23, 0.0 - a);
}
pub fn rotate_axis(&mut self, axis: Vec3, angle: f32)
pub fn rotate_axis(&mut self, axis: Vec3, angle: f32)
pub fn rotate_x(&mut self, angle: f32)
pub fn rotate_x(&mut self, angle: f32)
Rotates this Transform
around the X
axis by angle
(in radians).
If this Transform
has a parent, the axis is relative to the rotation of the parent.
Examples found in repository?
More examples
147 148 149 150 151 152 153 154 155 156 157 158 159 160
fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<FirstPassCube>>) {
for mut transform in &mut query {
transform.rotate_x(1.5 * time.delta_seconds());
transform.rotate_z(1.3 * time.delta_seconds());
}
}
/// Rotates the outer cube (main pass)
fn cube_rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<MainPassCube>>) {
for mut transform in &mut query {
transform.rotate_x(1.0 * time.delta_seconds());
transform.rotate_y(0.7 * time.delta_seconds());
}
}
pub fn rotate_y(&mut self, angle: f32)
pub fn rotate_y(&mut self, angle: f32)
Rotates this Transform
around the Y
axis by angle
(in radians).
If this Transform
has a parent, the axis is relative to the rotation of the parent.
Examples found in repository?
More examples
229 230 231 232 233 234 235 236 237 238 239 240
fn animate_light_direction(
time: Res<Time>,
mut query: Query<&mut Transform, With<DirectionalLight>>,
pause: Res<Pause>,
) {
if pause.0 {
return;
}
for mut transform in &mut query {
transform.rotate_y(time.delta_seconds() * PI / 5.0);
}
}
pub fn rotate_z(&mut self, angle: f32)
pub fn rotate_z(&mut self, angle: f32)
Rotates this Transform
around the Z
axis by angle
(in radians).
If this Transform
has a parent, the axis is relative to the rotation of the parent.
Examples found in repository?
More examples
pub fn rotate_local(&mut self, rotation: Quat)
pub fn rotate_local(&mut self, rotation: Quat)
pub fn rotate_local_axis(&mut self, axis: Vec3, angle: f32)
pub fn rotate_local_axis(&mut self, axis: Vec3, angle: f32)
Rotates this Transform
around its local axis
by angle
(in radians).
pub fn rotate_local_x(&mut self, angle: f32)
pub fn rotate_local_x(&mut self, angle: f32)
Rotates this Transform
around its local X
axis by angle
(in radians).
Examples found in repository?
More examples
pub fn rotate_local_y(&mut self, angle: f32)
pub fn rotate_local_y(&mut self, angle: f32)
Rotates this Transform
around its local Y
axis by angle
(in radians).
Examples found in repository?
More examples
pub fn rotate_local_z(&mut self, angle: f32)
pub fn rotate_local_z(&mut self, angle: f32)
Rotates this Transform
around its local Z
axis by angle
(in radians).
Examples found in repository?
More examples
pub fn translate_around(&mut self, point: Vec3, rotation: Quat)
pub fn translate_around(&mut self, point: Vec3, rotation: Quat)
pub fn rotate_around(&mut self, point: Vec3, rotation: Quat)
pub fn rotate_around(&mut self, point: Vec3, rotation: Quat)
Rotates this Transform
around a point
in space.
If this Transform
has a parent, the point
is relative to the Transform
of the parent.
Examples found in repository?
More examples
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
fn button_system(
interaction_query: Query<
(&Interaction, &TargetCamera, &RotateCamera),
(Changed<Interaction>, With<Button>),
>,
mut camera_query: Query<&mut Transform, With<Camera>>,
) {
for (interaction, target_camera, RotateCamera(direction)) in &interaction_query {
if let Interaction::Pressed = *interaction {
// Since TargetCamera propagates to the children, we can use it to find
// which side of the screen the button is on.
if let Ok(mut camera_transform) = camera_query.get_mut(target_camera.entity()) {
let angle = match direction {
Direction::Left => -0.1,
Direction::Right => 0.1,
};
camera_transform.rotate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, angle));
}
}
}
}
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
fn example_control_system(
mut materials: ResMut<Assets<StandardMaterial>>,
controllable: Query<(&Handle<StandardMaterial>, &ExampleControls)>,
mut camera: Query<(&mut Camera, &mut Transform, &GlobalTransform), With<Camera3d>>,
mut labels: Query<(&mut Style, &ExampleLabel)>,
mut display: Query<&mut Text, With<ExampleDisplay>>,
labelled: Query<&GlobalTransform>,
mut state: Local<ExampleState>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.pressed(KeyCode::ArrowUp) {
state.alpha = (state.alpha + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::ArrowDown) {
state.alpha = (state.alpha - time.delta_seconds()).max(0.0);
}
if input.just_pressed(KeyCode::Space) {
state.unlit = !state.unlit;
}
let randomize_colors = input.just_pressed(KeyCode::KeyC);
for (material_handle, controls) in &controllable {
let material = materials.get_mut(material_handle).unwrap();
material.base_color.set_a(state.alpha);
if controls.color && randomize_colors {
material.base_color.set_r(random());
material.base_color.set_g(random());
material.base_color.set_b(random());
}
if controls.unlit {
material.unlit = state.unlit;
}
}
let (mut camera, mut camera_transform, camera_global_transform) = camera.single_mut();
if input.just_pressed(KeyCode::KeyH) {
camera.hdr = !camera.hdr;
}
let rotation = if input.pressed(KeyCode::ArrowLeft) {
time.delta_seconds()
} else if input.pressed(KeyCode::ArrowRight) {
-time.delta_seconds()
} else {
0.0
};
camera_transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(rotation));
for (mut style, label) in &mut labels {
let world_position = labelled.get(label.entity).unwrap().translation() + Vec3::Y;
let viewport_position = camera
.world_to_viewport(camera_global_transform, world_position)
.unwrap();
style.top = Val::Px(viewport_position.y);
style.left = Val::Px(viewport_position.x);
}
let mut display = display.single_mut();
display.sections[0].value = format!(
" HDR: {}\nAlpha: {:.2}",
if camera.hdr { "ON " } else { "OFF" },
state.alpha
);
}
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
fn example_control_system(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
controllable: Query<(&Handle<StandardMaterial>, &ExampleControls)>,
mut camera: Query<
(
Entity,
&mut Camera,
&mut Camera3d,
&mut Transform,
Option<&DepthPrepass>,
Option<&TemporalJitter>,
),
With<Camera3d>,
>,
mut display: Query<&mut Text, With<ExampleDisplay>>,
mut state: Local<ExampleState>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.pressed(KeyCode::Digit2) {
state.diffuse_transmission = (state.diffuse_transmission + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::Digit1) {
state.diffuse_transmission = (state.diffuse_transmission - time.delta_seconds()).max(0.0);
}
if input.pressed(KeyCode::KeyW) {
state.specular_transmission = (state.specular_transmission + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::KeyQ) {
state.specular_transmission = (state.specular_transmission - time.delta_seconds()).max(0.0);
}
if input.pressed(KeyCode::KeyS) {
state.thickness = (state.thickness + time.delta_seconds()).min(5.0);
} else if input.pressed(KeyCode::KeyA) {
state.thickness = (state.thickness - time.delta_seconds()).max(0.0);
}
if input.pressed(KeyCode::KeyX) {
state.ior = (state.ior + time.delta_seconds()).min(3.0);
} else if input.pressed(KeyCode::KeyZ) {
state.ior = (state.ior - time.delta_seconds()).max(1.0);
}
if input.pressed(KeyCode::KeyI) {
state.reflectance = (state.reflectance + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::KeyU) {
state.reflectance = (state.reflectance - time.delta_seconds()).max(0.0);
}
if input.pressed(KeyCode::KeyR) {
state.perceptual_roughness = (state.perceptual_roughness + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::KeyE) {
state.perceptual_roughness = (state.perceptual_roughness - time.delta_seconds()).max(0.0);
}
let randomize_colors = input.just_pressed(KeyCode::KeyC);
for (material_handle, controls) in &controllable {
let material = materials.get_mut(material_handle).unwrap();
if controls.specular_transmission {
material.specular_transmission = state.specular_transmission;
material.thickness = state.thickness;
material.ior = state.ior;
material.perceptual_roughness = state.perceptual_roughness;
material.reflectance = state.reflectance;
}
if controls.diffuse_transmission {
material.diffuse_transmission = state.diffuse_transmission;
}
if controls.color && randomize_colors {
material.base_color.set_r(random());
material.base_color.set_g(random());
material.base_color.set_b(random());
}
}
let (
camera_entity,
mut camera,
mut camera_3d,
mut camera_transform,
depth_prepass,
temporal_jitter,
) = camera.single_mut();
if input.just_pressed(KeyCode::KeyH) {
camera.hdr = !camera.hdr;
}
#[cfg(not(all(feature = "webgl2", target_arch = "wasm32")))]
if input.just_pressed(KeyCode::KeyD) {
if depth_prepass.is_none() {
commands.entity(camera_entity).insert(DepthPrepass);
} else {
commands.entity(camera_entity).remove::<DepthPrepass>();
}
}
#[cfg(not(all(feature = "webgl2", target_arch = "wasm32")))]
if input.just_pressed(KeyCode::KeyT) {
if temporal_jitter.is_none() {
commands.entity(camera_entity).insert((
TemporalJitter::default(),
TemporalAntiAliasSettings::default(),
));
} else {
commands
.entity(camera_entity)
.remove::<(TemporalJitter, TemporalAntiAliasSettings)>();
}
}
if input.just_pressed(KeyCode::KeyO) && camera_3d.screen_space_specular_transmission_steps > 0 {
camera_3d.screen_space_specular_transmission_steps -= 1;
}
if input.just_pressed(KeyCode::KeyP) && camera_3d.screen_space_specular_transmission_steps < 4 {
camera_3d.screen_space_specular_transmission_steps += 1;
}
if input.just_pressed(KeyCode::KeyJ) {
camera_3d.screen_space_specular_transmission_quality = ScreenSpaceTransmissionQuality::Low;
}
if input.just_pressed(KeyCode::KeyK) {
camera_3d.screen_space_specular_transmission_quality =
ScreenSpaceTransmissionQuality::Medium;
}
if input.just_pressed(KeyCode::KeyL) {
camera_3d.screen_space_specular_transmission_quality = ScreenSpaceTransmissionQuality::High;
}
if input.just_pressed(KeyCode::Semicolon) {
camera_3d.screen_space_specular_transmission_quality =
ScreenSpaceTransmissionQuality::Ultra;
}
let rotation = if input.pressed(KeyCode::ArrowRight) {
state.auto_camera = false;
time.delta_seconds()
} else if input.pressed(KeyCode::ArrowLeft) {
state.auto_camera = false;
-time.delta_seconds()
} else if state.auto_camera {
time.delta_seconds() * 0.25
} else {
0.0
};
let distance_change =
if input.pressed(KeyCode::ArrowDown) && camera_transform.translation.length() < 25.0 {
time.delta_seconds()
} else if input.pressed(KeyCode::ArrowUp) && camera_transform.translation.length() > 2.0 {
-time.delta_seconds()
} else {
0.0
};
camera_transform.translation *= distance_change.exp();
camera_transform.rotate_around(
Vec3::ZERO,
Quat::from_euler(EulerRot::XYZ, 0.0, rotation, 0.0),
);
let mut display = display.single_mut();
display.sections[0].value = format!(
concat!(
" J / K / L / ; Screen Space Specular Transmissive Quality: {:?}\n",
" O / P Screen Space Specular Transmissive Steps: {}\n",
" 1 / 2 Diffuse Transmission: {:.2}\n",
" Q / W Specular Transmission: {:.2}\n",
" A / S Thickness: {:.2}\n",
" Z / X IOR: {:.2}\n",
" E / R Perceptual Roughness: {:.2}\n",
" U / I Reflectance: {:.2}\n",
" Arrow Keys Control Camera\n",
" C Randomize Colors\n",
" H HDR + Bloom: {}\n",
" D Depth Prepass: {}\n",
" T TAA: {}\n",
),
camera_3d.screen_space_specular_transmission_quality,
camera_3d.screen_space_specular_transmission_steps,
state.diffuse_transmission,
state.specular_transmission,
state.thickness,
state.ior,
state.perceptual_roughness,
state.reflectance,
if camera.hdr { "ON " } else { "OFF" },
if cfg!(any(not(feature = "webgl2"), not(target_arch = "wasm32"))) {
if depth_prepass.is_some() {
"ON "
} else {
"OFF"
}
} else {
"N/A (WebGL)"
},
if cfg!(any(not(feature = "webgl2"), not(target_arch = "wasm32"))) {
if temporal_jitter.is_some() {
if depth_prepass.is_some() {
"ON "
} else {
"N/A (Needs Depth Prepass)"
}
} else {
"OFF"
}
} else {
"N/A (WebGL)"
},
);
}
pub fn look_at(&mut self, target: Vec3, up: Vec3)
pub fn look_at(&mut self, target: Vec3, up: Vec3)
Rotates this Transform
so that Transform::forward
points towards the target
position,
and Transform::up
points towards up
.
In some cases it’s not possible to construct a rotation. Another axis will be picked in those cases:
- if
target
is the same as the transform translation,Vec3::Z
is used instead - if
up
is zero,Vec3::Y
is used instead - if the resulting forward direction is parallel with
up
, an orthogonal vector is used as the “right” direction
Examples found in repository?
More examples
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED)
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
time: Res<Time>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED * time.delta_seconds())
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
fn flicker_system(
mut flame: Query<&mut Transform, (With<Flicker>, With<Handle<Mesh>>)>,
mut light: Query<(&mut PointLight, &mut Transform), (With<Flicker>, Without<Handle<Mesh>>)>,
time: Res<Time>,
) {
let s = time.elapsed_seconds();
let a = (s * 6.0).cos() * 0.0125 + (s * 4.0).cos() * 0.025;
let b = (s * 5.0).cos() * 0.0125 + (s * 3.0).cos() * 0.025;
let c = (s * 7.0).cos() * 0.0125 + (s * 2.0).cos() * 0.025;
let (mut light, mut light_transform) = light.single_mut();
let mut flame_transform = flame.single_mut();
light.intensity = 4_000.0 + 3000.0 * (a + b + c);
flame_transform.translation = Vec3::new(-1.0, 1.23, 0.0);
flame_transform.look_at(Vec3::new(-1.0 - c, 1.7 - b, 0.0 - a), Vec3::X);
flame_transform.rotate(Quat::from_euler(EulerRot::XYZ, 0.0, 0.0, PI / 2.0));
light_transform.translation = Vec3::new(-1.0 - c, 1.7, 0.0 - a);
flame_transform.translation = Vec3::new(-1.0 - c, 1.23, 0.0 - a);
}
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
fn adjust_light_position(
input: Res<ButtonInput<KeyCode>>,
mut lights: Query<&mut Transform, With<Lights>>,
mut example_text: Query<&mut Text>,
) {
let mut offset = Vec3::ZERO;
if input.just_pressed(KeyCode::ArrowLeft) {
offset.x -= 1.0;
}
if input.just_pressed(KeyCode::ArrowRight) {
offset.x += 1.0;
}
if input.just_pressed(KeyCode::ArrowUp) {
offset.z -= 1.0;
}
if input.just_pressed(KeyCode::ArrowDown) {
offset.z += 1.0;
}
if input.just_pressed(KeyCode::PageDown) {
offset.y -= 1.0;
}
if input.just_pressed(KeyCode::PageUp) {
offset.y += 1.0;
}
if offset != Vec3::ZERO {
let mut example_text = example_text.single_mut();
for mut light in &mut lights {
light.translation += offset;
light.look_at(Vec3::ZERO, Vec3::Y);
example_text.sections[21].value = format!("{:.1},", light.translation.x);
example_text.sections[22].value = format!(" {:.1},", light.translation.y);
example_text.sections[23].value = format!(" {:.1}", light.translation.z);
}
}
}
pub fn look_to(&mut self, direction: Vec3, up: Vec3)
pub fn look_to(&mut self, direction: Vec3, up: Vec3)
Rotates this Transform
so that Transform::forward
points in the given direction
and Transform::up
points towards up
.
In some cases it’s not possible to construct a rotation. Another axis will be picked in those cases:
- if
direction
is zero,Vec3::NEG_Z
is used instead - if
up
is zero,Vec3::Y
is used instead - if
direction
is parallel withup
, an orthogonal vector is used as the “right” direction
Examples found in repository?
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
fn input_handler(
keyboard_input: Res<ButtonInput<KeyCode>>,
mesh_query: Query<&Handle<Mesh>, With<CustomUV>>,
mut meshes: ResMut<Assets<Mesh>>,
mut query: Query<&mut Transform, With<CustomUV>>,
time: Res<Time>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
let mesh_handle = mesh_query.get_single().expect("Query not successful");
let mesh = meshes.get_mut(mesh_handle).unwrap();
toggle_texture(mesh);
}
if keyboard_input.pressed(KeyCode::KeyX) {
for mut transform in &mut query {
transform.rotate_x(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyY) {
for mut transform in &mut query {
transform.rotate_y(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyZ) {
for mut transform in &mut query {
transform.rotate_z(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyR) {
for mut transform in &mut query {
transform.look_to(Vec3::NEG_Z, Vec3::Y);
}
}
}
pub fn mul_transform(&self, transform: Transform) -> Transform
pub fn mul_transform(&self, transform: Transform) -> Transform
Multiplies self
with transform
component by component, returning the
resulting Transform
pub fn transform_point(&self, point: Vec3) -> Vec3
pub fn transform_point(&self, point: Vec3) -> Vec3
Transforms the given point
, applying scale, rotation and translation.
If this Transform
has a parent, this will transform a point
that is
relative to the parent’s Transform
into one relative to this Transform
.
If this Transform
does not have a parent, this will transform a point
that is in global space into one relative to this Transform
.
If you want to transform a point
in global space to the local space of this Transform
,
consider using GlobalTransform::transform_point()
instead.
Trait Implementations§
§impl Animatable for Transform
impl Animatable for Transform
§fn blend(inputs: impl Iterator<Item = BlendInput<Transform>>) -> Transform
fn blend(inputs: impl Iterator<Item = BlendInput<Transform>>) -> Transform
§fn post_process(&mut self, _world: &World)
fn post_process(&mut self, _world: &World)
World
.
Most animatable types do not need to implement this.§impl Component for Transform
impl Component for Transform
§type Storage = TableStorage
type Storage = TableStorage
TableStorage
or SparseStorage
.§impl From<GlobalTransform> for Transform
impl From<GlobalTransform> for Transform
The transform is expected to be non-degenerate and without shearing, or the output will be invalid.
§fn from(transform: GlobalTransform) -> Transform
fn from(transform: GlobalTransform) -> Transform
§impl From<Transform> for GlobalTransform
impl From<Transform> for GlobalTransform
§fn from(transform: Transform) -> GlobalTransform
fn from(transform: Transform) -> GlobalTransform
§impl From<Transform> for SpatialBundle
impl From<Transform> for SpatialBundle
§fn from(transform: Transform) -> SpatialBundle
fn from(transform: Transform) -> SpatialBundle
§impl From<Transform> for TransformBundle
impl From<Transform> for TransformBundle
§fn from(transform: Transform) -> TransformBundle
fn from(transform: Transform) -> TransformBundle
§impl FromReflect for Transform
impl FromReflect for Transform
§fn from_reflect(reflect: &(dyn Reflect + 'static)) -> Option<Transform>
fn from_reflect(reflect: &(dyn Reflect + 'static)) -> Option<Transform>
Self
from a reflected value.§fn take_from_reflect(
reflect: Box<dyn Reflect>
) -> Result<Self, Box<dyn Reflect>>
fn take_from_reflect( reflect: Box<dyn Reflect> ) -> Result<Self, Box<dyn Reflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read more§impl GetTypeRegistration for Transform
impl GetTypeRegistration for Transform
§impl Mul<GlobalTransform> for Transform
impl Mul<GlobalTransform> for Transform
§type Output = GlobalTransform
type Output = GlobalTransform
*
operator.§fn mul(
self,
global_transform: GlobalTransform
) -> <Transform as Mul<GlobalTransform>>::Output
fn mul( self, global_transform: GlobalTransform ) -> <Transform as Mul<GlobalTransform>>::Output
*
operation. Read more§impl Mul<Transform> for GlobalTransform
impl Mul<Transform> for GlobalTransform
§impl Reflect for Transform
impl Reflect for Transform
§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any
.§fn into_reflect(self: Box<Transform>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Transform>) -> Box<dyn Reflect>
§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
§fn clone_value(&self) -> Box<dyn Reflect>
fn clone_value(&self) -> Box<dyn Reflect>
Reflect
trait object. Read more§fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>
§fn apply(&mut self, value: &(dyn Reflect + 'static))
fn apply(&mut self, value: &(dyn Reflect + 'static))
§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
§fn reflect_owned(self: Box<Transform>) -> ReflectOwned
fn reflect_owned(self: Box<Transform>) -> ReflectOwned
§fn reflect_partial_eq(&self, value: &(dyn Reflect + 'static)) -> Option<bool>
fn reflect_partial_eq(&self, value: &(dyn Reflect + 'static)) -> Option<bool>
§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
§fn serializable(&self) -> Option<Serializable<'_>>
fn serializable(&self) -> Option<Serializable<'_>>
§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
§impl Struct for Transform
impl Struct for Transform
§fn field(&self, name: &str) -> Option<&(dyn Reflect + 'static)>
fn field(&self, name: &str) -> Option<&(dyn Reflect + 'static)>
name
as a &dyn Reflect
.§fn field_mut(&mut self, name: &str) -> Option<&mut (dyn Reflect + 'static)>
fn field_mut(&mut self, name: &str) -> Option<&mut (dyn Reflect + 'static)>
name
as a
&mut dyn Reflect
.§fn field_at(&self, index: usize) -> Option<&(dyn Reflect + 'static)>
fn field_at(&self, index: usize) -> Option<&(dyn Reflect + 'static)>
index
as a
&dyn Reflect
.§fn field_at_mut(&mut self, index: usize) -> Option<&mut (dyn Reflect + 'static)>
fn field_at_mut(&mut self, index: usize) -> Option<&mut (dyn Reflect + 'static)>
index
as a &mut dyn Reflect
.§fn iter_fields(&self) -> FieldIter<'_> ⓘ
fn iter_fields(&self) -> FieldIter<'_> ⓘ
§fn clone_dynamic(&self) -> DynamicStruct
fn clone_dynamic(&self) -> DynamicStruct
DynamicStruct
.§impl TransformPoint for Transform
impl TransformPoint for Transform
§fn transform_point(&self, point: impl Into<Vec3>) -> Vec3
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3
§impl TypePath for Transform
impl TypePath for Transform
§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
impl Copy for Transform
impl StructuralPartialEq for Transform
Auto Trait Implementations§
impl RefUnwindSafe for Transform
impl Send for Transform
impl Sync for Transform
impl Unpin for Transform
impl UnwindSafe for Transform
Blanket Implementations§
§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut Components, storages: &mut Storages, ids: &mut impl FnMut(ComponentId) )
unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.§impl<T> DowncastSync for T
impl<T> DowncastSync for T
§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
fn get_components(self, func: &mut impl FnMut(StorageType, OwningPtr<'_>))
§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
.§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
.§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
.§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Self
using data from the given World
.§impl<T> GetPath for T
impl<T> GetPath for T
§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>
) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p> ) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>
path
. Read more§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>
) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p> ) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>
path
. Read more§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path
. Read more§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path
. Read more