messy push. Added lots of debugging/ development tools and updated camera entity

This commit is contained in:
2024-09-13 21:24:29 +02:00
parent 822c8bb7b5
commit b0fbfe1157
7 changed files with 1602 additions and 73 deletions

3
.cargo/config.toml Normal file
View File

@@ -0,0 +1,3 @@
# for Windows
[target.x86_64-pc-windows-msvc]
linker = "rust-lld.exe"

1061
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,10 @@ edition = "2021"
[dependencies] [dependencies]
avian3d = "0.1.2" avian3d = "0.1.2"
bevy = "0.14.2" bevy = { version = "0.14.2", features = ["file_watcher", "wayland"] }
bevy_editor_pls = "0.9.0"
leafwing-input-manager = "0.15.0"
#blenvy = "0.1.0-alpha.1"
log = { version = "*", features = ["max_level_debug", "release_max_level_warn"] } log = { version = "*", features = ["max_level_debug", "release_max_level_warn"] }
[features] [features]
@@ -32,3 +35,6 @@ strip = "debuginfo"
# "dpkg --add-architecture $CROSS_DEB_ARCH", # "dpkg --add-architecture $CROSS_DEB_ARCH",
# "apt-get update && apt-get --assume-yes install libudev-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH libasound2-dev:$CROSS_DEB_ARCH" # "apt-get update && apt-get --assume-yes install libudev-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH libasound2-dev:$CROSS_DEB_ARCH"
#] #]
[workspace]
resolver = "2" # Important! wgpu/Bevy needs this!

View File

@@ -1,5 +1,5 @@
[target.x86_64-unknown-linux-gnu] [target.x86_64-unknown-linux-gnu]
pre-build = [ pre-build = [
"dpkg --add-architecture $CROSS_DEB_ARCH", "dpkg --add-architecture $CROSS_DEB_ARCH",
"apt-get update && apt-get --assume-yes install libudev-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH libasound2-dev:$CROSS_DEB_ARCH" "apt-get update && apt-get --assume-yes install libudev-dev:$CROSS_DEB_ARCH libssl-dev:$CROSS_DEB_ARCH libasound2-dev:$CROSS_DEB_ARCH libwayland-client0:$CROSS_DEB_ARCH libwayland-dev:$CROSS_DEB_ARCH"
] ]

282
src/bck2_main.rs Normal file
View File

@@ -0,0 +1,282 @@
use bevy::{
math::vec3,
math::vec2,
math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume},
prelude::*
};
use bevy::diagnostic::FrameTimeDiagnosticsPlugin;
//paddle
const PADDLE_START_Y: f32 = 0.0;
const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
const PADDLE_SPEED: f32 = 500.0;
//ball
const BALL_COLOR: Color = Color::srgb(1.0, 0.54, 0.5);
const BALL_STARTING_POSITION: Vec3 = Vec3::new(0.0, -50.0, 1.0);
const BALL_SIZE: Vec2 = Vec2::new(30.0, 30.0);
const BALL_SPEED: f32 = 400.0;
const BALL_INITIAL_DIRECTION: Vec2 = Vec2::new(0.5, -0.5);
//wall
const LEFT_WALL: f32 = -450.0;
const RIGHT_WALL: f32 = 450.0;
const BOTTOM_WALL: f32 = -300.0;
const TOP_WALL: f32 = 300.0;
const WALL_THICKNESS: f32 = 10.0;
const WALL_BLOCK_WIDTH: f32 = RIGHT_WALL - LEFT_WALL;
const WALL_BLOCK_HEIGHT: f32 = TOP_WALL - BOTTOM_WALL;
const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Update, close_on_esc)
.add_systems(Startup, setup)
.add_plugins(FrameTimeDiagnosticsPlugin::default())
.add_systems(
FixedUpdate,
(
move_paddle,
apply_velocity,
check_ball_collision.after(apply_velocity),
),
)
.run();
}
#[derive(Component)]
struct Paddle;
#[derive(Component)]
struct Ball {
size: Vec2,
}
#[derive(Component, Deref, DerefMut)]
struct Velocity(Vec2);
#[derive(Component)]
struct Collider {
size: Vec2,
}
#[derive(Bundle)]
struct WallBundle{
sprite_bundle: SpriteBundle,
collider: Collider,
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
//camera
commands.spawn(Camera2dBundle::default());
//paddle
commands.spawn((
SpriteBundle {
transform: Transform {
translation: vec3(0., PADDLE_START_Y, 0.),
..default()
},
sprite: Sprite {
color: PADDLE_COLOR,
custom_size: Some(PADDLE_SIZE),
..default()
},
..default()
},
Paddle,
));
//ball
let ball_tex = asset_server.load("textures/circle.png");
commands.spawn((
SpriteBundle {
transform: Transform {
translation: BALL_STARTING_POSITION,
..default()
},
sprite: Sprite {
color: BALL_COLOR,
custom_size: Some(BALL_SIZE),
..default()
},
texture:ball_tex,
..default()
},
Ball { size: BALL_SIZE },
Velocity(BALL_SPEED * BALL_INITIAL_DIRECTION),
));
//walls
{
let vertical_wall_size = vec2(WALL_THICKNESS, WALL_BLOCK_HEIGHT + WALL_THICKNESS);
let horizontal_wall_size = vec2(WALL_BLOCK_WIDTH + WALL_THICKNESS, WALL_THICKNESS);
//left wall
commands.spawn(WallBundle {
sprite_bundle: SpriteBundle {
transform: Transform {
translation: vec3(LEFT_WALL, 0.0, 0.0),
..default()
},
sprite: Sprite {
color: WALL_COLOR,
custom_size: Some(vertical_wall_size),
..default()
},
..default()
},
collider: Collider {
size: vertical_wall_size,
},
});
//right wall
commands.spawn(WallBundle {
sprite_bundle: SpriteBundle {
transform: Transform {
translation: vec3(RIGHT_WALL, 0.0, 0.0),
..default()
},
sprite: Sprite {
color: WALL_COLOR,
custom_size: Some(vertical_wall_size),
..default()
},
..default()
},
collider: Collider {
size: vertical_wall_size,
},
});
//bottom wall
commands.spawn(WallBundle {
sprite_bundle: SpriteBundle {
transform: Transform {
translation: vec3(0.0, BOTTOM_WALL, 0.0),
..default()
},
sprite: Sprite {
color: WALL_COLOR,
custom_size: Some(horizontal_wall_size),
..default()
},
..default()
},
collider: Collider {
size: horizontal_wall_size,
},
});
//top wall
commands.spawn(WallBundle {
sprite_bundle: SpriteBundle {
transform: Transform {
translation: vec3(0.0, TOP_WALL, 0.0),
..default()
},
sprite: Sprite {
color: WALL_COLOR,
custom_size: Some(horizontal_wall_size),
..default()
},
..default()
},
collider: Collider {
size: horizontal_wall_size,
},
});
}
}
fn move_paddle(
input: Res<ButtonInput<KeyCode>>,
time_step: Res<Time<Fixed>>,
mut query: Query<&mut Transform, With<Paddle>>,
) {
let mut paddle_transform = query.single_mut();
let mut direction: f32 = 0.0;
if input.pressed(KeyCode::KeyA) {
direction -= 1.0
}
if input.pressed(KeyCode::KeyD) {
direction += 1.0;
}
let mut new_x =
paddle_transform.translation.x + direction * PADDLE_SPEED * time_step.delta_seconds();
new_x = new_x.min(RIGHT_WALL - (WALL_THICKNESS + PADDLE_SIZE.x) * 0.5);
new_x = new_x.max(LEFT_WALL + (WALL_THICKNESS + PADDLE_SIZE.x) * 0.5);
paddle_transform.translation.x = new_x;
}
fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time_step: Res<Time<Fixed>>) {
let dt = time_step.delta_seconds();
for (mut transform, velocity) in &mut query {
transform.translation.x += velocity.x * dt;
transform.translation.y += velocity.y * dt;
}
}
fn check_ball_collision(
mut ball_query: Query<(&mut Velocity, &Transform, &Ball)>,
collider_query: Query<(&Transform, &Collider)>,
) {
for (mut ball_velocity, ball_transform, ball) in &mut ball_query {
for (transform, other) in &collider_query {
let collision = ball_collision(
ball_transform.translation,
ball.size,
transform.translation,
other.size,
);
let mut reflect_x = false;
let mut reflect_y = false;
if let Some(collision) = collision {
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,
Collision::Inside => { /* do nothing */ }
}
if reflect_x {
ball_velocity.x *= -1.;
}
if reflect_y {
ball_velocity.y *= -1.;
}
}
}
}
}
fn ball_collision() {
}
pub fn close_on_esc(
mut commands: Commands,
focused_windows: Query<(Entity, &Window)>,
input: Res<ButtonInput<KeyCode>>,
) {
for (window, focus) in focused_windows.iter() {
if !focus.focused {
continue;
}
if input.just_pressed(KeyCode::Escape) {
commands.entity(window).despawn();
}
}
}

50
src/bck_main.rs Normal file
View File

@@ -0,0 +1,50 @@
use bevy::prelude::*;
#[derive(Component)]
struct Person;
#[derive(Component)]
struct Name(String);
#[derive(Resource)]
struct GreetTimer(Timer);
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());
}
}
fn main() {
App::new()
.add_plugins(HelloPlugin)
.add_plugins(DefaultPlugins)
.run();
}
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("Zayna Nieves".to_string())));
}
fn greet_people(time: Res<Time>, mut timer: ResMut<GreetTimer>, query: Query<&Name, With<Person>>) {
if timer.0.tick(time.delta()).just_finished() {
for name in &query {
println!("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;
}
}
}

View File

@@ -1,55 +1,138 @@
// disable console on windows for release builds
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use bevy::{ use bevy::{
//bevy_dev_tools::fps_overlay::{FpsOverlayConfig, FpsOverlayPlugin}, //bevy_dev_tools::fps_overlay::{FpsOverlayConfig, FpsOverlayPlugin},
prelude::* asset::LoadedFolder,
input::common_conditions::input_just_pressed,
color::palettes::tailwind,
input::mouse::MouseMotion,
pbr::NotShadowCaster,
prelude::*,
render::view::RenderLayers,
window::{CursorGrabMode, PrimaryWindow},
}; };
use avian3d::prelude::*; use avian3d::prelude::*;
use bevy_editor_pls::prelude::*;
use leafwing_input_manager::prelude::*;
fn main() { fn main() {
App::new() App::new()
.insert_resource(GreetTimer(Timer::from_seconds(2.5, TimerMode::Repeating))) .insert_resource(GreetTimer(Timer::from_seconds(2.5, TimerMode::Repeating)))
.add_systems(Update, (close_on_esc, spawn_block)) .add_systems(
Update,
(
//close_on_esc,
spawn_block,
move_camera,
toggle_mouse.run_if(input_just_pressed(KeyCode::Escape)),
//move_player,
//change_fov
),
)
.add_plugins(( .add_plugins((
DefaultPlugins, DefaultPlugins,
PhysicsPlugins::default(), PhysicsPlugins::default(),
/*FpsOverlayPlugin { EditorPlugin::default(),
config: FpsOverlayConfig {
text_config: TextStyle {
// Here we define size of our overlay
font_size: 50.0,y
// We can also change color of the overlay
color: Color::srgb(0.0, 1.0, 0.0),
// If we want, we can use a custom font
font: default(),
},
},
},*/
)) ))
//.add_plugins(FrameTimeDiagnosticsPlugin::default()) .add_systems(
.add_systems(Startup, setup) Startup,
(
setup,
cursor_grab,
//spawn_view_model,
//spawn_world_model,
),
)
.run(); .run();
} }
//#[derive(Component)] #[derive(Component)]
//struct Ground; struct Player;
#[derive(Component)]
struct WorldModelCamera;
#[derive(Resource)] #[derive(Resource)]
struct GreetTimer(Timer); struct GreetTimer(Timer);
#[derive(Component)]
pub struct FPSCamera {
pub speed: f32,
pub sensitivity: f32,
pub rotate_lock: f32,
pub rotation: Vec3,
pub recoil_shake: Vec3,
pub camera_shake_readjustment_factor: f32,
}
/// Used implicitly by all entities without a `RenderLayers` component.
/// Our world model camera and all objects other than the player are on this layer.
/// The light source belongs to both layers.
const DEFAULT_RENDER_LAYER: usize = 0;
/// Used by the view model camera and the player's arm.
/// The light source belongs to both layers.
const VIEW_MODEL_RENDER_LAYER: usize = 1;
fn cursor_grab (
mut q_windows: Query<&mut Window, With<PrimaryWindow>>,
) {
let mut primary_window = q_windows.single_mut();
// if you want to use the cursor, but not let it leave the window,
// use `Confined` mode:
//primary_window.cursor.grab_mode = CursorGrabMode::Confined;
// for a game that doesn't use the cursor (like a shooter):
// use `Locked` mode to keep the cursor in one place
primary_window.cursor.grab_mode = CursorGrabMode::Locked;
// also hide the cursor
primary_window.cursor.visible = false;
}
/* fn cursor_ungrab(
mut q_windows: Query<&mut Window, With<PrimaryWindow>>,
) {
let mut primary_window = q_windows.single_mut();
primary_window.cursor.grab_mode = CursorGrabMode::None;
primary_window.cursor.visible = true;
} */
#[derive(Component)]
struct Customcomponent;
fn setup( fn setup(
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
asset_server: Res<AssetServer>,
) { ) {
// custom test
commands.spawn((
PbrBundle {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(Color::srgb_u8(255, 144, 124)),
transform: Transform::from_xyz(0.0, 2.0, 0.0),
..default()
},
Customcomponent,
RigidBody::Dynamic,
Collider::cuboid(1.0, 1.0, 1.0),
));
// floor // floor
commands.spawn(( commands.spawn((
PbrBundle { PbrBundle {
mesh: meshes.add(Plane3d::default().mesh().size(20., 20.)), mesh: meshes.add(Plane3d::default().mesh().size(100., 100.)),
material: materials.add(Color::srgb(0.3, 0.5, 0.3)), material: materials.add(Color::srgb(0.3, 0.5, 0.3)),
..default() ..default()
}, },
RigidBody::Static, RigidBody::Static,
Collider::cuboid(20.0, 0.0, 20.0), Collider::cuboid(100.0, 0.0, 100.0),
//Ground,
)); ));
// Dynamic physics object with a collision shape and initial angular velocity // Dynamic physics object with a collision shape and initial angular velocity
@@ -72,13 +155,60 @@ fn setup(
}); });
// camera // camera
commands.spawn(Camera3dBundle { /*commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y), transform: Transform::from_xyz(15.0, 5.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
..default() ..default()
});*/
// view_ model() - The *view model* is the model that represents the player's body
let arm = meshes.add(Cuboid::new(0.1, 0.1, 0.5));
let arm_materlial = materials.add(Color::from(tailwind::TEAL_200));
// Player
commands
.spawn(SpatialBundle {
visibility: Visibility::Visible,
transform: Transform::from_xyz(10., 0., 5.)
.looking_at(Vec3::ZERO, Vec3::Y),
..default()
})
.with_children(|child| {
child.spawn((
Visibility::Visible,
Camera3dBundle {
/*projection: Projection::Perspective((PerspectiveProjection {
//fov: (103.0 / 360.0) * (std::f32::consts::PI * 2.0),
fov: 90.,
..Default::default()
})),*/
transform: Transform::from_xyz(0.0, 1.0, 4.0),
..default()
},
RigidBody::Dynamic,
LockedAxes::new().lock_rotation_x().lock_rotation_y().lock_rotation_z(),
//LockedAxes::new().lock_rotation_y(),
//LockedAxes::new().lock_rotation_z(),
LinearVelocity(Vec3::new(0.0, 0.0, 0.0)),
AngularVelocity(Vec3::new(0.0, 0.0, 0.0)),
Collider::cuboid(0.2, 1.4, 0.2),
FPSCamera {
camera_shake_readjustment_factor: 0.3,
recoil_shake: Vec3::ZERO,
rotation: Vec3::new(0., 0., 0.),
speed: 300.,
rotate_lock: 88. * 0.0174533,
//sensitivity: (0.173) / 900.,
sensitivity: 0.0008,
},
LinearDamping(4.),
AngularDamping(1.0),
GravityScale(1.),
//Player,
));
}); });
} }
pub fn close_on_esc( /*pub fn close_on_esc(
mut commands: Commands, mut commands: Commands,
focused_windows: Query<(Entity, &Window)>, focused_windows: Query<(Entity, &Window)>,
input: Res<ButtonInput<KeyCode>>, input: Res<ButtonInput<KeyCode>>,
@@ -92,6 +222,21 @@ pub fn close_on_esc(
commands.entity(window).despawn(); commands.entity(window).despawn();
} }
} }
}*/
fn toggle_mouse(mut window: Query<&mut Window, With<PrimaryWindow>>) {
for mut window in &mut window {
match window.cursor.grab_mode {
CursorGrabMode::None => {
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
CursorGrabMode::Confined | CursorGrabMode::Locked => {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
}
} }
fn spawn_block( fn spawn_block(
@@ -112,7 +257,77 @@ fn spawn_block(
}, },
RigidBody::Dynamic, RigidBody::Dynamic,
Collider::cuboid(1.0, 1.0, 1.0), Collider::cuboid(1.0, 1.0, 1.0),
AngularVelocity(Vec3::new(1.5, 2.5, 0.5)), AngularVelocity(Vec3::new(2.0, 3.5, 1.0)),
)); ));
} }
} }
pub fn move_camera(
//cursor_lock_state: Res<>,
q_windows: Query<&Window, With<PrimaryWindow>>,
//mut q_windows: Query<&mut Window, With<PrimaryWindow>>,
mut motion_evr: EventReader<MouseMotion>,
time: Res<Time>,
mut camera_query: Query<(&mut Transform, &mut FPSCamera)>,
) {
let primary_window = q_windows.single();
//let mut primary_window = q_windows.single_mut();
//primary_window.cursor.grab_mode = CursorGrabMode::None;
//info!("MODE: {}", primary_window.cursor.grab_mode);
//if cursor_lock_state.state {
//info!("IM HERE");
if primary_window.cursor.grab_mode == CursorGrabMode::Locked{
//info!("MODE ACTIVE");
for (mut transform, mut camera) in camera_query.iter_mut() {
for ev in motion_evr.read() {
camera.rotation.y -= ev.delta.x * camera.sensitivity;
camera.rotation.x -= ev.delta.y * camera.sensitivity;
camera.rotation.x =
f32::clamp(camera.rotation.x, -camera.rotate_lock, camera.rotate_lock);
//transform.rotation += Quat::from_axis_angle(Vec3::new(0., 1., 0.), angle);
//println!("{}",x_quat);
}
/*camera.recoil_shake = move_towards(
camera.recoil_shake,
Vec3::ZERO,
time.delta_seconds() * camera.camera_shake_readjustment_factor,
);*/
let x_quat = Quat::from_axis_angle(
Vec3::new(0., 1., 0.),
//camera.rotation.y - camera.recoil_shake.x,
camera.rotation.y
);
let y_quat = Quat::from_axis_angle(
Vec3::new(1., 0., 0.),
//camera.rotation.x + camera.recoil_shake.y,
camera.rotation.x
);
transform.rotation = x_quat * y_quat;
}
}
}
/*fn change_fov (
input: Res<ButtonInput<KeyCode>>,
mut world_model_projection: Query<&mut Projection, With<WorldModelCamera>>,
) {
let mut projection = world_model_projection.single_mut();
let Projection::Perspective(ref mut perspective) = projection.as_mut() else {
unreachable!(
"The `Projection` component was explicitly built with `Projection::Perspective`"
);
};
if input.pressed(KeyCode::ArrowUp) {
perspective.fov -= 1.0_f32.to_radians();
perspective.fov = perspective.fov.max(20.0_f32.to_radians());
}
if input.pressed(KeyCode::ArrowDown) {
perspective.fov += 1.0_f32.to_radians();
perspective.fov = perspective.fov.min(160.0_f32.to_radians());
}
}*/