//! This example showcases how to implement 2D screen shake.1//! It follows the GDC talk ["Math for Game Programmers: Juicing Your Cameras With Math"](https://www.youtube.com/watch?v=tu-Qe66AvtY) by Squirrel Eiserloh2//!3//! The key features are:4//! - Camera shake is dependent on a "trauma" value between 0.0 and 1.0. The more trauma, the stronger the shake.5//! - Trauma automatically decays over time.6//! - The camera shake will always only affect the camera `Transform` up to a maximum displacement.7//! - The camera's `Transform` is only affected by the shake for the rendering. The `Transform` stays "normal" for the rest of the game logic.8//! - All displacements are governed by a noise function, guaranteeing that the shake is smooth and continuous.9//! This means that the camera won't jump around wildly.10//!11//! ## Controls12//!13//! | Key Binding | Action |14//! |:---------------------------------|:---------------------------|15//! | Space (pressed repeatedly) | Increase camera trauma |1617use bevy::{18input::common_conditions::input_just_pressed, math::ops::powf, prelude::*,19sprite_render::MeshMaterial2d,20};2122// Before we implement the code, let's quickly introduce the underlying constants.23// They are later encoded in a `CameraShakeConfig` component, but introduced here so we can easily tweak them.24// Try playing around with them and see how the shake behaves!2526/// The trauma decay rate controls how quickly the trauma decays.27/// 0.5 means that a full trauma of 1.0 will decay to 0.0 in 2 seconds.28const TRAUMA_DECAY_PER_SECOND: f32 = 0.5;2930/// The trauma exponent controls how the trauma affects the shake.31/// Camera shakes don't feel punchy when they go up linearly, so we use an exponent of 2.0.32/// The higher the exponent, the more abrupt is the transition between no shake and full shake.33const TRAUMA_EXPONENT: f32 = 2.0;3435/// The maximum angle the camera can rotate on full trauma.36/// 10.0 degrees is a somewhat high but still reasonable shake. Try bigger values for something more silly and wiggly.37const MAX_ANGLE: f32 = 10.0_f32.to_radians();3839/// The maximum translation the camera will move on full trauma in both the x and y directions.40/// 20.0 px is a low enough displacement to not be distracting. Try higher values for an effect that looks like the camera is wandering around.41const MAX_TRANSLATION: f32 = 20.0;4243/// How much we are traversing the noise function in arbitrary units per second.44/// This dictates how fast the camera shakes.45/// 20.0 is a fairly fast shake. Try lower values for a more dreamy effect.46const NOISE_SPEED: f32 = 20.0;4748/// How much trauma we add per press of the space key.49/// A value of 1.0 would mean that a single press would result in a maximum trauma, i.e. 1.0.50const TRAUMA_PER_PRESS: f32 = 0.4;5152fn main() {53App::new()54.add_plugins(DefaultPlugins)55.add_systems(Startup, (setup_scene, setup_instructions, setup_camera))56// At the start of the frame, restore the camera's transform to its unshaken state.57.add_systems(PreUpdate, reset_transform)58.add_systems(59Update,60// Increase trauma when the space key is pressed.61increase_trauma.run_if(input_just_pressed(KeyCode::Space)),62)63// Just before the end of the frame, apply the shake.64// This is ordered so that the transform propagation produces correct values for the global transform, which is used by Bevy's rendering.65.add_systems(PostUpdate, shake_camera.before(TransformSystems::Propagate))66.run();67}6869/// Let's start with the core mechanic: how do we shake the camera?70/// This system runs right at the end of the frame, so that we can sneak in the shake effect before rendering kicks in.71fn shake_camera(72camera_shake: Single<(&mut CameraShakeState, &CameraShakeConfig, &mut Transform)>,73time: Res<Time>,74) {75let (mut camera_shake, config, mut transform) = camera_shake.into_inner();7677// Before we even start thinking about the shake, we save the original transform so it's not lost.78// At the start of the next frame, we will restore the camera's transform to this original transform.79camera_shake.original_transform = *transform;8081// To generate the transform offset, we use a noise function. Noise is like a random number generator, but cooler.82// Let's start with a visual intuition: <https://assets-global.website-files.com/64b6d182aee713bd0401f4b9/64b95974ec292aabac45fc8e_image.png>83// The image on the left is made from pure randomness, the image on the right is made from a kind of noise called Perlin noise.84// Notice how the noise has much more "structure" than the randomness? How it looks like it has peaks and valleys?85// This property makes noise very desirable for a variety of visual effects. In our case, what we want is that the86// camera does not wildly teleport around the world, but instead *moves* through the world frame by frame.87// We can use 1D Perlin noise for this, which takes one input and outputs a value between -1.0 and 1.0. If we increase the input by a little bit,88// like by the time since the last frame, we get a different output that is still "close" to the previous one.8990// This is the input to the noise function. Just using the elapsed time is pretty good input,91// since it means that noise generations that are close in time will be close in output.92// We simply multiply it by a constant to be able to "speed up" or "slow down" the noise.93let t = time.elapsed_secs() * config.noise_speed;9495// Now we generate three noise values. One for the rotation, one for the x-offset, and one for the y-offset.96// But if we generated those three noise values with the same input, we would get the same output three times!97// To avoid this, we simply add a random offset to each input.98// You can think of this as the seed value you would give a random number generator.99let rotation_noise = perlin_noise::generate(t + 0.0);100let x_noise = perlin_noise::generate(t + 100.0);101let y_noise = perlin_noise::generate(t + 200.0);102103// Games often deal with linear increments. For example, if an enemy deals 10 damage and attacks you 2 times, you will take 20 damage.104// But that's not how impact feels! Human senses are much more attuned to exponential changes.105// So, we make sure that the `shake` value we use is an exponential function of the trauma.106// But doesn't this make the value explode? Fortunately not: since `trauma` is between 0.0 and 1.0, exponentiating it will actually make it smaller!107// See <https://www.wolframalpha.com/input?i=plot+x+and+x%5E2+and+x%5E3+for+x+in+%5B0%2C+1%5D> for a graph.108let shake = powf(camera_shake.trauma, config.exponent);109110// Now, to get the final offset, we multiply this noise value by the shake value and the maximum value.111// The noise value is in [-1, 1], so by multiplying it with a maximum value, we get a value in [-max_value, +max_value].112// Multiply this by the shake value to get the exponential effect, and we're done!113let roll_offset = rotation_noise * shake * config.max_angle;114let x_offset = x_noise * shake * config.max_translation;115let y_offset = y_noise * shake * config.max_translation;116117// Finally, we apply the offset to the camera's transform. Since we already stored the original transform,118// and this system runs right at the end of the frame, we can't accidentally break any game logic by changing the transform.119transform.translation.x += x_offset;120transform.translation.y += y_offset;121transform.rotate_z(roll_offset);122123// Some bookkeeping at the end: trauma should decay over time.124camera_shake.trauma -= config.trauma_decay_per_second * time.delta_secs();125camera_shake.trauma = camera_shake.trauma.clamp(0.0, 1.0);126}127128/// Increase the trauma when the space key is pressed.129fn increase_trauma(mut camera_shake: Single<&mut CameraShakeState>) {130camera_shake.trauma += TRAUMA_PER_PRESS;131camera_shake.trauma = camera_shake.trauma.clamp(0.0, 1.0);132}133134/// Restore the camera's transform to its unshaken state.135/// Runs at the start of the frame, so that gameplay logic doesn't need to care about camera shake.136fn reset_transform(camera_shake: Single<(&CameraShakeState, &mut Transform)>) {137let (camera_shake, mut transform) = camera_shake.into_inner();138*transform = camera_shake.original_transform;139}140141/// The current state of the camera shake that is updated every frame.142#[derive(Component, Debug, Default)]143struct CameraShakeState {144/// The current trauma level in [0.0, 1.0].145trauma: f32,146/// The original transform of the camera before applying the shake.147/// We store this so that we can restore the camera's transform to its original state at the start of the next frame.148original_transform: Transform,149}150151/// Configuration for the camera shake.152/// See the constants at the top of the file for some good default values and detailed explanations.153#[derive(Component, Debug)]154#[require(CameraShakeState)]155struct CameraShakeConfig {156trauma_decay_per_second: f32,157exponent: f32,158max_angle: f32,159max_translation: f32,160noise_speed: f32,161}162163fn setup_camera(mut commands: Commands) {164commands.spawn((165Camera2d,166// Enable camera shake for this camera.167CameraShakeConfig {168trauma_decay_per_second: TRAUMA_DECAY_PER_SECOND,169exponent: TRAUMA_EXPONENT,170max_angle: MAX_ANGLE,171max_translation: MAX_TRANSLATION,172noise_speed: NOISE_SPEED,173},174));175}176177/// Spawn a scene so we have something to look at.178fn setup_scene(179mut commands: Commands,180mut meshes: ResMut<Assets<Mesh>>,181mut materials: ResMut<Assets<ColorMaterial>>,182) {183// Background tile184commands.spawn((185Mesh2d(meshes.add(Rectangle::new(1000., 700.))),186MeshMaterial2d(materials.add(Color::srgb(0.2, 0.2, 0.3))),187));188189// The shape in the middle could be our player character.190commands.spawn((191Mesh2d(meshes.add(Rectangle::new(50.0, 100.0))),192MeshMaterial2d(materials.add(Color::srgb(0.25, 0.94, 0.91))),193Transform::from_xyz(0., 0., 2.),194));195196// These two shapes could be obstacles.197commands.spawn((198Mesh2d(meshes.add(Rectangle::new(50.0, 50.0))),199MeshMaterial2d(materials.add(Color::srgb(0.85, 0.0, 0.2))),200Transform::from_xyz(-450.0, 200.0, 2.),201));202203commands.spawn((204Mesh2d(meshes.add(Rectangle::new(70.0, 50.0))),205MeshMaterial2d(materials.add(Color::srgb(0.5, 0.8, 0.2))),206Transform::from_xyz(450.0, -150.0, 2.),207));208}209210fn setup_instructions(mut commands: Commands) {211commands.spawn((212Text::new("Press space repeatedly to trigger a progressively stronger screen shake"),213Node {214position_type: PositionType::Absolute,215bottom: px(12),216left: px(12),217..default()218},219));220}221222/// Tiny 1D Perlin noise implementation. The mathematical details are not important here.223mod perlin_noise {224use super::*;225226pub fn generate(x: f32) -> f32 {227// Left coordinate of the unit-line that contains the input.228let x_floor = x.floor() as usize;229230// Input location in the unit-line.231let xf0 = x - x_floor as f32;232let xf1 = xf0 - 1.0;233234// Wrap to range 0-255.235let xi0 = x_floor & 0xFF;236let xi1 = (x_floor + 1) & 0xFF;237238// Apply the fade function to the location.239let t = fade(xf0).clamp(0.0, 1.0);240241// Generate hash values for each point of the unit-line.242let h0 = PERMUTATION_TABLE[xi0];243let h1 = PERMUTATION_TABLE[xi1];244245// Linearly interpolate between dot products of each gradient with its distance to the input location.246let a = dot_grad(h0, xf0);247let b = dot_grad(h1, xf1);248a.interpolate_stable(&b, t)249}250251// A cubic curve that smoothly transitions from 0 to 1 as t goes from 0 to 1252fn fade(t: f32) -> f32 {253t * t * t * (t * (t * 6.0 - 15.0) + 10.0)254}255256fn dot_grad(hash: u8, xf: f32) -> f32 {257// In 1D case, the gradient may be either 1 or -1.258// The distance vector is the input offset (relative to the smallest bound).259if hash & 0x1 != 0 {260xf261} else {262-xf263}264}265266// Perlin noise permutation table. This is a random sequence of the numbers 0-255.267const PERMUTATION_TABLE: [u8; 256] = [2680x97, 0xA0, 0x89, 0x5B, 0x5A, 0x0F, 0x83, 0x0D, 0xC9, 0x5F, 0x60, 0x35, 0xC2, 0xE9, 0x07,2690xE1, 0x8C, 0x24, 0x67, 0x1E, 0x45, 0x8E, 0x08, 0x63, 0x25, 0xF0, 0x15, 0x0A, 0x17, 0xBE,2700x06, 0x94, 0xF7, 0x78, 0xEA, 0x4B, 0x00, 0x1A, 0xC5, 0x3E, 0x5E, 0xFC, 0xDB, 0xCB, 0x75,2710x23, 0x0B, 0x20, 0x39, 0xB1, 0x21, 0x58, 0xED, 0x95, 0x38, 0x57, 0xAE, 0x14, 0x7D, 0x88,2720xAB, 0xA8, 0x44,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