Проектная работа - MVP
Создание нового проекта
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
/// Эксперименты в ходе прохождения туториала:
|
||||
/// https://github.com/fogarecious/bevy_tutorial
|
||||
use bevy::{prelude::*, winit::WinitSettings};
|
||||
use tracing::Level;
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
// .add_plugins(MinimalPlugins)
|
||||
.add_plugins(
|
||||
DefaultPlugins
|
||||
.build()
|
||||
.set(bevy::log::LogPlugin {
|
||||
level: Level::INFO,
|
||||
filter: "wgpu_hal=warn,bevy_learning=trace".to_string(),
|
||||
// fmt_layer: |_| snake_game::define_log_layer(),
|
||||
..Default::default()
|
||||
})
|
||||
.set(TaskPoolPlugin {
|
||||
task_pool_options: TaskPoolOptions::with_num_threads(1),
|
||||
}),
|
||||
)
|
||||
.insert_resource(WinitSettings::desktop_app())
|
||||
.insert_resource(ClearColor(Color::srgb(0.3, 0.6, 0.8)))
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(PostStartup, (print_all_entities, inspect))
|
||||
.run();
|
||||
}
|
||||
|
||||
fn setup(mut commands: Commands, _window: Query<&Window>, _world: &World) {
|
||||
let _window = _window.single().unwrap();
|
||||
|
||||
let _root = commands
|
||||
.spawn((
|
||||
Sprite::from_color(Color::srgb(1., 1., 1.), Vec2::new(100., 100.)),
|
||||
Transform {
|
||||
translation: vec3(0., 0., 0.),
|
||||
// scale: Vec3::new(1., 1., 1.),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let _red = commands
|
||||
.spawn((
|
||||
Sprite::from_color(Color::srgb(1., 0., 0.), Vec2::new(30., 30.)),
|
||||
Transform {
|
||||
translation: vec3(-20., 30., 0.),
|
||||
..Default::default()
|
||||
},
|
||||
ChildOf(_root),
|
||||
))
|
||||
.id();
|
||||
let _blue = commands
|
||||
.spawn((
|
||||
Sprite::from_color(Color::srgb(0., 0., 1.), Vec2::new(20., 20.)),
|
||||
Transform {
|
||||
translation: vec3(20., 30., 0.),
|
||||
..Default::default()
|
||||
},
|
||||
ChildOf(_root),
|
||||
))
|
||||
.id();
|
||||
|
||||
commands.spawn(Camera2d);
|
||||
}
|
||||
|
||||
fn print_all_entities(mut commands: Commands, query: Query<Entity>) {
|
||||
for entity in query {
|
||||
commands.entity(entity).log_components();
|
||||
}
|
||||
}
|
||||
|
||||
fn inspect(mut _commands: Commands, _query: Query<Entity>) {}
|
||||
@@ -0,0 +1,49 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
fn main() {
|
||||
App::new().add_plugins(DefaultPlugins).add_plugins(HelloPlugin).run();
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct Person;
|
||||
|
||||
#[derive(Component)]
|
||||
struct Name(String);
|
||||
|
||||
#[derive(Resource)]
|
||||
struct GreetTimer(Timer);
|
||||
|
||||
fn add_people(mut commands: Commands) {
|
||||
commands.spawn((Person, Name("Elaina Proctor".to_string())));
|
||||
commands.spawn((Person, Name("Renzo Hume".to_string())));
|
||||
commands.spawn((Person, Name("Zaina Nieves".to_string())));
|
||||
}
|
||||
|
||||
fn greet_people(time: Res<Time>, mut timer: ResMut<GreetTimer>, query: Query<&Name, With<Person>>) {
|
||||
// update uor timer with the time elapsed since the last update
|
||||
// if that causes the timer to finish, we say hello to everyone
|
||||
if timer.0.tick(time.delta()).just_finished() {
|
||||
for name in &query {
|
||||
info!("hello {}!", name.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_people(mut query: Query<&mut Name, With<Person>>) {
|
||||
for mut name in &mut query {
|
||||
if name.0 == "Elaina Proctor" {
|
||||
name.0 = "Elaina Hume".to_string();
|
||||
break; // We don't need to change any other names.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HelloPlugin;
|
||||
|
||||
impl Plugin for HelloPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(GreetTimer(Timer::from_seconds(2.0, TimerMode::Repeating)));
|
||||
app.add_systems(Startup, add_people);
|
||||
app.add_systems(Update, (update_people, greet_people).chain());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Example of how to draw to a texture from the CPU.
|
||||
//!
|
||||
//! You can set the values of individual pixels to whatever you want.
|
||||
//! Bevy provides user-friendly APIs that work with [`Color`]
|
||||
//! values and automatically perform any necessary conversions and encoding
|
||||
//! into the texture's native pixel format.
|
||||
|
||||
use bevy::asset::RenderAssetUsages;
|
||||
use bevy::color::{color_difference::EuclideanDistance, palettes::css};
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
|
||||
use rand::{RngExt, SeedableRng};
|
||||
use rand_chacha::ChaCha8Rng;
|
||||
|
||||
const IMAGE_WIDTH: u32 = 256;
|
||||
const IMAGE_HEIGHT: u32 = 256;
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
.add_plugins(DefaultPlugins)
|
||||
// In this example, we will use a fixed timestep to draw a pattern on the screen
|
||||
// one pixel at a time, so the pattern will gradually emerge over time, and
|
||||
// the speed at which it appears is not tied to the framerate.
|
||||
// Let's make the fixed update very fast, so it doesn't take too long. :)
|
||||
.insert_resource(Time::<Fixed>::from_hz(1024.0))
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(FixedUpdate, draw)
|
||||
.run();
|
||||
}
|
||||
|
||||
/// Store the image handle that we will draw to, here.
|
||||
#[derive(Resource)]
|
||||
struct MyProcGenImage(Handle<Image>);
|
||||
|
||||
#[derive(Resource)]
|
||||
struct SeededRng(ChaCha8Rng);
|
||||
|
||||
fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
|
||||
commands.spawn(Camera2d);
|
||||
|
||||
// Create an image that we are going to draw into
|
||||
let mut image = Image::new_fill(
|
||||
// 2D image of size 256x256
|
||||
Extent3d {
|
||||
width: IMAGE_WIDTH,
|
||||
height: IMAGE_HEIGHT,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
TextureDimension::D2,
|
||||
// Initialize it with a beige color
|
||||
&(css::BEIGE.to_u8_array()),
|
||||
// Use the same encoding as the color we set
|
||||
TextureFormat::Rgba8UnormSrgb,
|
||||
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
|
||||
);
|
||||
|
||||
// To make it extra fancy, we can set the Alpha of each pixel,
|
||||
// so that it fades out in a circular fashion.
|
||||
for y in 0..IMAGE_HEIGHT {
|
||||
for x in 0..IMAGE_WIDTH {
|
||||
let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
|
||||
let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
|
||||
let r = Vec2::new(x as f32, y as f32).distance(center);
|
||||
let a = 1.0 - (r / max_radius).clamp(0.0, 1.0);
|
||||
|
||||
// Here we will set the A value by accessing the raw data bytes.
|
||||
// (it is the 4th byte of each pixel, as per our `TextureFormat`)
|
||||
|
||||
// Find our pixel by its coordinates
|
||||
let pixel_bytes = image.pixel_bytes_mut(UVec3::new(x, y, 0)).unwrap();
|
||||
// Convert our f32 to u8
|
||||
pixel_bytes[3] = (a * u8::MAX as f32) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
// Add it to Bevy's assets, so it can be used for rendering
|
||||
// this will give us a handle we can use
|
||||
// (to display it in a sprite, or as part of UI, etc.)
|
||||
let handle = images.add(image);
|
||||
|
||||
// Create a sprite entity using our image
|
||||
commands.spawn(Sprite::from_image(handle.clone()));
|
||||
commands.insert_resource(MyProcGenImage(handle));
|
||||
|
||||
// We're seeding the PRNG here to make this example deterministic for testing purposes.
|
||||
// This isn't strictly required in practical use unless you need your app to be deterministic.
|
||||
let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
|
||||
commands.insert_resource(SeededRng(seeded_rng));
|
||||
}
|
||||
|
||||
/// Every fixed update tick, draw one more pixel to make a spiral pattern
|
||||
fn draw(
|
||||
my_handle: Res<MyProcGenImage>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
// Used to keep track of where we are
|
||||
mut i: Local<u32>,
|
||||
mut draw_color: Local<Color>,
|
||||
mut seeded_rng: ResMut<SeededRng>,
|
||||
) {
|
||||
if *i == 0 {
|
||||
// Generate a random color on first run.
|
||||
*draw_color = Color::linear_rgb(seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random());
|
||||
}
|
||||
|
||||
// Get the image from Bevy's asset storage.
|
||||
let image = images.get_mut(&my_handle.0).expect("Image not found");
|
||||
|
||||
// Compute the position of the pixel to draw.
|
||||
|
||||
let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
|
||||
let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
|
||||
let rot_speed = 0.0123;
|
||||
let period = 0.12345;
|
||||
|
||||
let r = ops::sin(*i as f32 * period) * max_radius;
|
||||
let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
|
||||
let (x, y) = (xy.x as u32, xy.y as u32);
|
||||
|
||||
// Get the old color of that pixel.
|
||||
let old_color = image.get_color_at(x, y).unwrap();
|
||||
|
||||
// If the old color is our current color, change our drawing color.
|
||||
let tolerance = 1.0 / 255.0;
|
||||
if old_color.distance(&draw_color) <= tolerance {
|
||||
*draw_color = Color::linear_rgb(seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random());
|
||||
}
|
||||
|
||||
// Set the new color, but keep old alpha value from image.
|
||||
image.set_color_at(x, y, draw_color.with_alpha(old_color.alpha())).unwrap();
|
||||
|
||||
*i += 1;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use bevy::{
|
||||
platform::collections::{HashMap, HashSet},
|
||||
prelude::*,
|
||||
};
|
||||
use rand::{RngExt, SeedableRng};
|
||||
use rand_chacha::ChaCha8Rng;
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
.add_plugins(DefaultPlugins)
|
||||
.init_resource::<SpatialIndex>()
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(Update, (draw_shapes, handle_click))
|
||||
// Observers are systems that run when an event is "triggered". This observer runs whenever
|
||||
// `ExplodeMines` is triggered.
|
||||
.add_observer(
|
||||
|explode_mines: On<ExplodeMines>, mines: Query<&Mine>, index: Res<SpatialIndex>, mut commands: Commands| {
|
||||
// Access resources
|
||||
for entity in index.get_nearby(explode_mines.pos) {
|
||||
// Run queries
|
||||
let mine = mines.get(entity).unwrap();
|
||||
if mine.pos.distance(explode_mines.pos) < mine.size + explode_mines.radius {
|
||||
// And queue commands, including triggering additional events
|
||||
// Here we trigger the `Explode` event for entity `e`
|
||||
commands.trigger(Explode { entity });
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
// This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
|
||||
.add_observer(on_add_mine)
|
||||
// This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
|
||||
// and removes it from the spatial index.
|
||||
.add_observer(on_remove_mine)
|
||||
.run();
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct Mine {
|
||||
pos: Vec2,
|
||||
size: f32,
|
||||
}
|
||||
|
||||
impl Mine {
|
||||
fn random(rand: &mut ChaCha8Rng) -> Self {
|
||||
Mine {
|
||||
pos: Vec2::new((rand.random::<f32>() - 0.5) * 1200.0, (rand.random::<f32>() - 0.5) * 600.0),
|
||||
size: 4.0 + rand.random::<f32>() * 16.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a normal [`Event`]. Any observer that watches for it will run when it is triggered.
|
||||
#[derive(Event)]
|
||||
struct ExplodeMines {
|
||||
pos: Vec2,
|
||||
radius: f32,
|
||||
}
|
||||
|
||||
/// An [`EntityEvent`] is a specialized type of [`Event`] that can target a specific entity. In addition to
|
||||
/// running normal "top level" observers when it is triggered (which target _any_ entity that Explodes), it will
|
||||
/// also run any observers that target the _specific_ entity for that event.
|
||||
#[derive(EntityEvent)]
|
||||
struct Explode {
|
||||
entity: Entity,
|
||||
}
|
||||
|
||||
fn setup(mut commands: Commands) {
|
||||
commands.spawn(Camera2d);
|
||||
commands.spawn((
|
||||
Text::new(
|
||||
"Click on a \"Mine\" to trigger it.\n\
|
||||
When it explodes it will trigger all overlapping mines.",
|
||||
),
|
||||
Node {
|
||||
position_type: PositionType::Absolute,
|
||||
top: px(12),
|
||||
left: px(12),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
|
||||
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
|
||||
|
||||
commands
|
||||
.spawn(Mine::random(&mut rng))
|
||||
// Observers can watch for events targeting a specific entity.
|
||||
// This will create a new observer that runs whenever the Explode event
|
||||
// is triggered for this spawned entity.
|
||||
.observe(explode_mine);
|
||||
|
||||
// We want to spawn a bunch of mines. We could just call the code above for each of them.
|
||||
// That would create a new observer instance for every Mine entity. Having duplicate observers
|
||||
// generally isn't worth worrying about as the overhead is low. But if you want to be maximally efficient,
|
||||
// you can reuse observers across entities.
|
||||
//
|
||||
// First, observers are actually just entities with the Observer component! The `observe()` functions
|
||||
// you've seen so far in this example are just shorthand for manually spawning an observer.
|
||||
let mut observer = Observer::new(explode_mine);
|
||||
|
||||
// As we spawn entities, we can make this observer watch each of them:
|
||||
for _ in 0..1000 {
|
||||
let entity = commands.spawn(Mine::random(&mut rng)).id();
|
||||
observer.watch_entity(entity);
|
||||
}
|
||||
|
||||
// By spawning the Observer component, it becomes active!
|
||||
commands.spawn(observer);
|
||||
}
|
||||
|
||||
fn on_add_mine(add: On<Add, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
|
||||
let mine = query.get(add.entity).unwrap();
|
||||
let tile = ((mine.pos.x / CELL_SIZE).floor() as i32, (mine.pos.y / CELL_SIZE).floor() as i32);
|
||||
index.map.entry(tile).or_default().insert(add.entity);
|
||||
}
|
||||
|
||||
// Remove despawned mines from our index
|
||||
fn on_remove_mine(remove: On<Remove, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
|
||||
let mine = query.get(remove.entity).unwrap();
|
||||
let tile = ((mine.pos.x / CELL_SIZE).floor() as i32, (mine.pos.y / CELL_SIZE).floor() as i32);
|
||||
index.map.entry(tile).and_modify(|set| {
|
||||
set.remove(&remove.entity);
|
||||
});
|
||||
}
|
||||
|
||||
fn explode_mine(explode: On<Explode>, query: Query<&Mine>, mut commands: Commands) {
|
||||
// Explode is an EntityEvent. `explode.entity` is the entity that Explode was triggered for.
|
||||
let Ok(mut entity) = commands.get_entity(explode.entity) else {
|
||||
return;
|
||||
};
|
||||
info!("Boom! {} exploded.", explode.entity);
|
||||
entity.despawn();
|
||||
let mine = query.get(explode.entity).unwrap();
|
||||
// Trigger another explosion cascade.
|
||||
commands.trigger(ExplodeMines {
|
||||
pos: mine.pos,
|
||||
radius: mine.size,
|
||||
});
|
||||
}
|
||||
|
||||
// Draw a circle for each mine using `Gizmos`
|
||||
fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
|
||||
for mine in &mines {
|
||||
gizmos.circle_2d(mine.pos, mine.size, Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8));
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger `ExplodeMines` at the position of a given click
|
||||
fn handle_click(
|
||||
mouse_button_input: Res<ButtonInput<MouseButton>>,
|
||||
camera: Single<(&Camera, &GlobalTransform)>,
|
||||
windows: Query<&Window>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let Ok(windows) = windows.single() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (camera, camera_transform) = *camera;
|
||||
if let Some(pos) = windows
|
||||
.cursor_position()
|
||||
.and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
|
||||
.map(|ray| ray.origin.truncate())
|
||||
&& mouse_button_input.just_pressed(MouseButton::Left)
|
||||
{
|
||||
commands.trigger(ExplodeMines { pos, radius: 1.0 });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
struct SpatialIndex {
|
||||
map: HashMap<(i32, i32), HashSet<Entity>>,
|
||||
}
|
||||
|
||||
/// Cell size has to be bigger than any `TriggerMine::radius`
|
||||
const CELL_SIZE: f32 = 64.0;
|
||||
|
||||
impl SpatialIndex {
|
||||
// Lookup all entities within adjacent cells of our spatial index
|
||||
fn get_nearby(&self, pos: Vec2) -> Vec<Entity> {
|
||||
let tile = ((pos.x / CELL_SIZE).floor() as i32, (pos.y / CELL_SIZE).floor() as i32);
|
||||
let mut nearby = Vec::new();
|
||||
for x in -1..2 {
|
||||
for y in -1..2 {
|
||||
if let Some(mines) = self.map.get(&(tile.0 + x, tile.1 + y)) {
|
||||
nearby.extend(mines.iter());
|
||||
}
|
||||
}
|
||||
}
|
||||
nearby
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use bevy::math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume};
|
||||
use bevy::prelude::*;
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
.add_plugins(DefaultPlugins)
|
||||
.insert_resource(ClearColor(Color::srgb(0.8, 0.8, 1.0)))
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(FixedUpdate, (move_paddle, apply_velocity, check_for_collisions))
|
||||
.run();
|
||||
}
|
||||
|
||||
const PADDLE_GAP_Y: f32 = 50.0;
|
||||
const PADDLE_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
|
||||
const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
|
||||
const PADDLE_SPEED: f32 = 500.0;
|
||||
const PADDLE_PADDING: f32 = 10.0;
|
||||
|
||||
const LEFT_WALL: f32 = -600.0;
|
||||
const RIGHT_WALL: f32 = 600.0;
|
||||
const BOTTOM_WALL: f32 = -300.0;
|
||||
const TOP_WALL: f32 = 300.0;
|
||||
const WALL_WIDTH: f32 = 20.0;
|
||||
|
||||
const BALL_START_POS: Vec2 = Vec2::new(0.0, -100.0);
|
||||
const BALL_COLOR: Color = Color::srgb(0.2, 0.5, 0.2);
|
||||
const BALL_DIAMETER: f32 = 20.0;
|
||||
const INIT_BALL_SPEED: Vec2 = Vec2::new(100.0, 100.0);
|
||||
|
||||
#[derive(Component)]
|
||||
struct Paddle;
|
||||
|
||||
#[derive(Component)]
|
||||
struct Ball;
|
||||
|
||||
#[derive(Component)]
|
||||
struct Collider;
|
||||
|
||||
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>) {
|
||||
commands.spawn(Camera2d);
|
||||
|
||||
let paddle_y = BOTTOM_WALL + PADDLE_GAP_Y;
|
||||
commands.spawn((
|
||||
Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
|
||||
Transform {
|
||||
translation: Vec3::new(0.0, paddle_y, 0.0),
|
||||
scale: PADDLE_SIZE.extend(1.0),
|
||||
..Default::default()
|
||||
},
|
||||
Paddle,
|
||||
Collider,
|
||||
));
|
||||
|
||||
commands.spawn((
|
||||
Mesh2d(meshes.add(Circle::default())),
|
||||
MeshMaterial2d(materials.add(BALL_COLOR)),
|
||||
Transform {
|
||||
translation: BALL_START_POS.extend(0.0),
|
||||
scale: Vec3::splat(BALL_DIAMETER),
|
||||
..Default::default()
|
||||
},
|
||||
Velocity(INIT_BALL_SPEED),
|
||||
Ball,
|
||||
));
|
||||
|
||||
commands.spawn(Wall::new(WallLocation::Left));
|
||||
commands.spawn(Wall::new(WallLocation::Right));
|
||||
commands.spawn(Wall::new(WallLocation::Top));
|
||||
commands.spawn(Wall::new(WallLocation::Bottom));
|
||||
}
|
||||
|
||||
fn move_paddle(input: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut paddle_transform: Single<&mut Transform, With<Paddle>>) {
|
||||
let direction = if input.pressed(KeyCode::ArrowLeft) {
|
||||
-1.0
|
||||
} else if input.pressed(KeyCode::ArrowRight) {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let new_pos = paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
|
||||
|
||||
const LEFT_BOUND: f32 = LEFT_WALL + WALL_WIDTH / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
|
||||
const RIGHT_BOUND: f32 = RIGHT_WALL - WALL_WIDTH / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
|
||||
|
||||
paddle_transform.translation.x = new_pos.clamp(LEFT_BOUND, RIGHT_BOUND);
|
||||
}
|
||||
|
||||
#[derive(Component, Deref, DerefMut)]
|
||||
struct Velocity(Vec2);
|
||||
|
||||
fn apply_velocity(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
|
||||
for (mut transform, velocity) in &mut query {
|
||||
transform.translation += velocity.extend(0.0) * time.delta_secs();
|
||||
}
|
||||
}
|
||||
|
||||
fn check_for_collisions(ball_query: Single<(&mut Velocity, &Transform), With<Ball>>, collider_query: Query<&Transform, With<Collider>>) {
|
||||
let (mut ball_velocity, ball_transform) = ball_query.into_inner();
|
||||
|
||||
for collider_transform in &collider_query {
|
||||
let collision = ball_collision(
|
||||
BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.0),
|
||||
Aabb2d::new(collider_transform.translation.truncate(), collider_transform.scale.truncate() / 2.0),
|
||||
);
|
||||
|
||||
if let Some(collision) = collision {
|
||||
let mut reflect_x = false;
|
||||
let mut reflect_y = false;
|
||||
|
||||
match collision {
|
||||
Collision::Left => reflect_x = ball_velocity.x > 0.0,
|
||||
Collision::Right => reflect_x = ball_velocity.x < 0.0,
|
||||
Collision::Top => reflect_y = ball_velocity.y < 0.0,
|
||||
Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
|
||||
};
|
||||
|
||||
if reflect_x {
|
||||
ball_velocity.x *= -1.0;
|
||||
}
|
||||
|
||||
if reflect_y {
|
||||
ball_velocity.y *= -1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Collision {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
fn ball_collision(circle: BoundingCircle, rect: Aabb2d) -> Option<Collision> {
|
||||
if !circle.intersects(&rect) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let closest = rect.closest_point(circle.center());
|
||||
let offset = circle.center() - closest;
|
||||
|
||||
let side = if offset.x.abs() > offset.y.abs() {
|
||||
if offset.x < 0.0 { Collision::Left } else { Collision::Right }
|
||||
} else if offset.y > 0.0 {
|
||||
Collision::Top
|
||||
} else {
|
||||
Collision::Bottom
|
||||
};
|
||||
|
||||
Some(side)
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
#[require(Sprite, Transform)]
|
||||
struct Wall;
|
||||
|
||||
impl Wall {
|
||||
pub fn new(location: WallLocation) -> (Wall, Sprite, Transform, Collider) {
|
||||
(
|
||||
Wall,
|
||||
Sprite::from_color(Color::srgb(1.0, 0.4, 0.4), Vec2::ONE),
|
||||
Transform {
|
||||
translation: location.position().extend(0.0),
|
||||
scale: location.size().extend(1.0),
|
||||
..Default::default()
|
||||
},
|
||||
Collider,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum WallLocation {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl WallLocation {
|
||||
fn position(&self) -> Vec2 {
|
||||
match self {
|
||||
WallLocation::Left => Vec2::new(LEFT_WALL, 0.0),
|
||||
WallLocation::Right => Vec2::new(RIGHT_WALL, 0.0),
|
||||
WallLocation::Top => Vec2::new(0.0, TOP_WALL),
|
||||
WallLocation::Bottom => Vec2::new(0.0, BOTTOM_WALL),
|
||||
}
|
||||
}
|
||||
|
||||
fn size(&self) -> Vec2 {
|
||||
match self {
|
||||
WallLocation::Left | WallLocation::Right => Vec2::new(WALL_WIDTH, TOP_WALL - BOTTOM_WALL),
|
||||
WallLocation::Top | WallLocation::Bottom => Vec2::new(RIGHT_WALL - LEFT_WALL, WALL_WIDTH),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
fn main() {
|
||||
App::new() //
|
||||
.add_plugins(DefaultPlugins)
|
||||
.add_systems(PreStartup, pre_startup)
|
||||
.add_systems(Startup, (startup, setup))
|
||||
.add_systems(PostStartup, post_startup)
|
||||
.add_systems(First, first)
|
||||
.add_systems(PreUpdate, pre_update)
|
||||
.add_systems(Update, (update, check_space_pressed))
|
||||
.add_systems(PostUpdate, post_update)
|
||||
.run();
|
||||
}
|
||||
|
||||
fn pre_startup() {
|
||||
info!("PreStartup");
|
||||
}
|
||||
|
||||
fn startup() {
|
||||
info!("Startup");
|
||||
}
|
||||
|
||||
fn post_startup() {
|
||||
info!("PostStartup");
|
||||
}
|
||||
|
||||
fn first() {
|
||||
info!("First");
|
||||
}
|
||||
|
||||
fn pre_update() {
|
||||
info!("PreUpdate");
|
||||
}
|
||||
|
||||
fn update() {
|
||||
info!("Update");
|
||||
}
|
||||
|
||||
fn post_update() {
|
||||
info!("PostUpdate");
|
||||
}
|
||||
|
||||
fn check_space_pressed(input: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
|
||||
if input.just_pressed(KeyCode::Space) {
|
||||
commands.trigger(TestEvent0);
|
||||
}
|
||||
}
|
||||
|
||||
fn setup(mut commands: Commands) {
|
||||
commands.spawn((Observer::new(test_event_0_handler),));
|
||||
commands.spawn((Observer::new(test_event_1_handler),));
|
||||
}
|
||||
|
||||
#[derive(Event, Debug)]
|
||||
struct TestEvent0;
|
||||
|
||||
#[derive(Event, Debug)]
|
||||
struct TestEvent1;
|
||||
|
||||
fn test_event_0_handler(event: On<TestEvent0>, mut commands: Commands) {
|
||||
info!("handle {:?}", event.event());
|
||||
commands.trigger(TestEvent1);
|
||||
}
|
||||
|
||||
fn test_event_1_handler(event: On<TestEvent1>, mut commands: Commands) {
|
||||
info!("handle {:?}", event.event());
|
||||
commands.trigger(TestEvent0);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! An example that illustrates how Time is handled in ECS.
|
||||
|
||||
use bevy::{app::AppExit, prelude::*};
|
||||
|
||||
use std::{
|
||||
io::{self, BufRead},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
fn banner() {
|
||||
println!("This example is meant to intuitively demonstrate how Time works in Bevy.");
|
||||
println!();
|
||||
println!("Time will be printed in three different schedules in the app:");
|
||||
println!("- PreUpdate: real time is printed");
|
||||
println!("- FixedUpdate: fixed time step time is printed, may be run zero or multiple times");
|
||||
println!("- Update: virtual game time is printed");
|
||||
println!();
|
||||
println!("Max delta time is set to 5 seconds. Fixed timestep is set to 1 second.");
|
||||
println!();
|
||||
}
|
||||
|
||||
fn help() {
|
||||
println!("The app reads commands line-by-line from standard input.");
|
||||
println!();
|
||||
println!("Commands:");
|
||||
println!(" empty line: Run app.update() once on the Bevy App");
|
||||
println!(" q: Quit the app.");
|
||||
println!(" f: Set speed to fast, 2x");
|
||||
println!(" n: Set speed to normal, 1x");
|
||||
println!(" s: Set speed to slow, 0.5x");
|
||||
println!(" p: Pause");
|
||||
println!(" u: Unpause");
|
||||
}
|
||||
|
||||
fn runner(mut app: App) -> AppExit {
|
||||
banner();
|
||||
help();
|
||||
let stdin = io::stdin();
|
||||
for line in stdin.lock().lines() {
|
||||
if let Err(err) = line {
|
||||
println!("read err: {err:#}");
|
||||
break;
|
||||
}
|
||||
match line.unwrap().as_str() {
|
||||
"" => {
|
||||
app.update();
|
||||
}
|
||||
"f" => {
|
||||
println!("FAST: setting relative speed to 2x");
|
||||
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(2.0);
|
||||
}
|
||||
"n" => {
|
||||
println!("NORMAL: setting relative speed to 1x");
|
||||
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(1.0);
|
||||
}
|
||||
"s" => {
|
||||
println!("SLOW: setting relative speed to 0.5x");
|
||||
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(0.5);
|
||||
}
|
||||
"p" => {
|
||||
println!("PAUSE: pausing virtual clock");
|
||||
app.world_mut().resource_mut::<Time<Virtual>>().pause();
|
||||
}
|
||||
"u" => {
|
||||
println!("UNPAUSE: resuming virtual clock");
|
||||
app.world_mut().resource_mut::<Time<Virtual>>().unpause();
|
||||
}
|
||||
"q" => {
|
||||
println!("QUITTING!");
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
help();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AppExit::Success
|
||||
}
|
||||
|
||||
fn print_real_time(time: Res<Time<Real>>) {
|
||||
println!(
|
||||
"PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
|
||||
time.delta(),
|
||||
time.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
fn print_fixed_time(time: Res<Time>) {
|
||||
println!(
|
||||
"FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
|
||||
time.delta(),
|
||||
time.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
fn print_time(time: Res<Time>) {
|
||||
println!(
|
||||
"Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
|
||||
time.delta(),
|
||||
time.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
.add_plugins(MinimalPlugins)
|
||||
.insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
|
||||
.insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
|
||||
.add_systems(PreUpdate, print_real_time)
|
||||
.add_systems(FixedUpdate, print_fixed_time)
|
||||
.add_systems(Update, print_time)
|
||||
.set_runner(runner)
|
||||
.run();
|
||||
}
|
||||
Reference in New Issue
Block a user