Skip to content

Commit

Permalink
<Fixed>issue #2 & #3
Browse files Browse the repository at this point in the history
close issue  #2 &  #3
  • Loading branch information
cloudhu committed Dec 13, 2024
1 parent afe5455 commit fb8acdf
Show file tree
Hide file tree
Showing 10 changed files with 147 additions and 73 deletions.
16 changes: 16 additions & 0 deletions .idea/csv-editor.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ bevy_asset_loader = { version = "0.22.0", features = [
] }
bevy_kira_audio = { version = "0.21.0", features = ["ogg","mp3", "wav"] }
rand = "0.9.0-alpha.2"
#bevy-parallax = "0.10.0"
bevy-parallax = { git = "https://github.com/foxzool/bevy-parallax.git", rev = "0322b9d" }
bevy_prototype_lyon = "0.13.0"
serde = "1.0.210"
serde_json = "1.0.128"
Expand Down
9 changes: 3 additions & 6 deletions src/components/player.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::components::character::{Character, CharacterType};
use crate::components::spawnable::SpawnPosition;
use crate::gameplay::player::PlayerComponent;
use bevy::prelude::{Bundle, Component, Deref, DerefMut, Resource, Vec2};

/// Parameters for how to spawn new players. By default, the player can do anything.
Expand Down Expand Up @@ -30,7 +31,7 @@ pub struct PlayerData {
}

/// Input method for a player
/// Gamepad has a usize identifier
/// Gamepad has an usize identifier
#[derive(Clone, PartialEq, Debug, Copy)]
pub enum PlayerInput {
Keyboard,
Expand Down Expand Up @@ -146,7 +147,7 @@ pub struct PlayerOutgoingDamageComponent {
pub projectile_size: f32,
/// Base projectile count
pub projectile_count: usize,
/// Starting cooldown multiplier of the player. Used in calculating the the `cooldown_multiplier`
/// Starting cooldown multiplier of the player. Used in calculating the `cooldown_multiplier`
pub base_cooldown_multiplier: f32,
/// Multiplier for how long abilities take to be ready for use again
pub cooldown_multiplier: f32,
Expand All @@ -172,10 +173,6 @@ pub struct PlayerInventoryComponent {
pub money: usize,
}

/// Flag for Player Entities
#[derive(Component)]
pub struct PlayerComponent;

impl From<&Character> for PlayerMovementComponent {
fn from(character: &Character) -> Self {
Self {
Expand Down
42 changes: 42 additions & 0 deletions src/gameplay/camera.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use crate::ship::engine::Engine;
use crate::util::Math;
use crate::{CameraShake, MainCamera};
use bevy::prelude::*;
use bevy_parallax::ParallaxMoveEvent;
use crate::gameplay::player::PlayerComponent;

pub fn camera_follow(
time: Res<Time>,
player_q: Query<&Transform, (With<Engine>, With<PlayerComponent>)>,
mut camera_q: Query<
(Entity, &Transform, &mut CameraShake),
(With<Transform>, With<MainCamera>),
>,
mut move_event_writer: EventWriter<ParallaxMoveEvent>,
) {
if let Ok((camera_entity, camera_transform, mut shake)) = camera_q.get_single_mut() {
// info!("camera transform: {:?}", camera_transform);
if let Ok(player_transform) = player_q.get_single() {
// info!("player transform: {:?}", player_transform);
// Calculate the new camera position based on the player's position
let target_position = Vec2::new(
player_transform.translation.x + 1.0,
player_transform.translation.y,
);

let current_position = camera_transform.translation.truncate();

let smooth_move_position = current_position
.lerp(target_position, 5.0 * time.delta_secs())
+ shake.trauma * Math::random_2d_unit_vector();

shake.trauma = f32::max(shake.trauma - shake.decay * time.delta_secs(), 0.0);

move_event_writer.send(ParallaxMoveEvent {
translation: smooth_move_position - current_position,
camera: camera_entity,
rotation: camera_transform.rotation.z,
});
}
}
}
3 changes: 3 additions & 0 deletions src/gameplay/gamelogic.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::assets::audio_assets::{AudioAssets, Fonts};
use crate::components::health::Health;
use crate::config::GameConfig;
use crate::gameplay::camera::camera_follow;
use crate::gameplay::effects::{FloatingText, HitFlash};
use crate::gameplay::loot::{DropsLoot, IsLoot, Points, WorthPoints};
use crate::gameplay::physics::{Collider, Physics};
Expand All @@ -15,6 +16,7 @@ use bevy::prelude::*;
use bevy::time::Stopwatch;
use bevy_kira_audio::prelude::Volume;
use bevy_kira_audio::{Audio, AudioControl};
use bevy_parallax::ParallaxSystems;
use bevy_prototype_lyon::prelude::{GeometryBuilder, ShapeBundle, Stroke};
use bevy_prototype_lyon::shapes;
use rand::Rng;
Expand Down Expand Up @@ -107,6 +109,7 @@ pub(super) fn plugin(app: &mut App) {
Update,
(
game_time_system,
camera_follow.before(ParallaxSystems),
combat_system,
take_damage_events,
death_system,
Expand Down
2 changes: 2 additions & 0 deletions src/gameplay/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! The game's main gameplay states and transitions between them.
mod camera;
pub mod effects;
pub mod gamelogic;
mod hud;
Expand All @@ -10,6 +11,7 @@ pub mod physics;
pub mod player;
mod selection;
mod upgrade;

use bevy::prelude::*;

pub(super) fn plugin(app: &mut App) {
Expand Down
4 changes: 2 additions & 2 deletions src/gameplay/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,13 @@ pub fn player_control(
});
if world_cursor_pos.is_some() {
engine.target = world_cursor_pos;
info!("Player controlled at {:?}", engine.target);
// info!("Player controlled at {:?}", engine.target);
}
} else if intent != Vec2::ZERO {
let player_pos = trans.translation.clone();
engine.target =
Option::from(Vec2::new(player_pos.x + intent.x, player_pos.y + intent.y));
info!("Player moved to {:?}", engine.target);
// info!("Player moved to {:?}", engine.target);
} else {
engine.target = None;
}
Expand Down
118 changes: 61 additions & 57 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ mod ship;
mod theme;
mod util;

use crate::util::RenderLayer;
use bevy::core_pipeline::bloom::{Bloom, BloomCompositeMode};
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::{asset::AssetMetaCheck, prelude::*};
use bevy_kira_audio::{AudioPlugin, AudioSettings};
use bevy_prototype_lyon::prelude::ShapePlugin;
// use bevy_parallax::{
// CreateParallaxEvent, LayerData, LayerSpeed, ParallaxCameraComponent, ParallaxPlugin,
// };
use bevy_parallax::{
CreateParallaxEvent, LayerData, LayerSpeed, ParallaxCameraComponent, ParallaxPlugin,
};
use bevy_prototype_lyon::prelude::{GeometryBuilder, ShapeBundle, ShapePlugin};
use bevy_prototype_lyon::shapes;

pub struct AppPlugin;

impl Plugin for AppPlugin {
Expand Down Expand Up @@ -60,7 +63,7 @@ impl Plugin for AppPlugin {
)
.insert_resource(ClearColor(Color::srgb(0.04, 0.005, 0.04)))
.add_plugins(ShapePlugin)
// .add_plugins(ParallaxPlugin)
.add_plugins(ParallaxPlugin)
.add_plugins(AudioPlugin);

// Spawn the main camera.
Expand Down Expand Up @@ -113,61 +116,62 @@ impl Default for CameraShake {
}
}

// mut create_parallax: EventWriter<CreateParallaxEvent>
fn spawn_camera(mut commands: Commands) {
// spawn camera and create parallax background
fn spawn_camera(mut commands: Commands, mut create_parallax: EventWriter<CreateParallaxEvent>) {
// Spawn the Camera
commands.spawn((
Name::new("Camera"),
Camera2d,
Camera {
hdr: true, // 1. HDR is required for bloom
..default()
},
Tonemapping::TonyMcMapface,
MainCamera,
CameraShake::default(),
Bloom {
// 3. Enable bloom for the camera
intensity: 0.15,
composite_mode: BloomCompositeMode::Additive,
..default()
},
// Render all UI to this camera.
// Not strictly necessary since we only use one camera,
// but if we don't use this component, our UI will disappear as soon
// as we add another camera. This includes indirect ways of adding cameras like using
// [ui node outlines](https://bevyengine.org/news/bevy-0-14/#ui-node-outline-gizmos)
// for debugging. So it's good to have this here for future-proofing.
IsDefaultUiCamera,
));
// .insert(ParallaxCameraComponent::default())//TODO:bevy-parallax plugin need to be updated
// .id();
let camera = commands
.spawn((
Name::new("Camera"),
Camera2d,
Camera {
hdr: true, // 1. HDR is required for bloom
..default()
},
Tonemapping::TonyMcMapface,
MainCamera,
CameraShake::default(),
Bloom {
// 3. Enable bloom for the camera
intensity: 0.15,
composite_mode: BloomCompositeMode::Additive,
..default()
},
// Render all UI to this camera.
// Not strictly necessary since we only use one camera,
// but if we don't use this component, our UI will disappear as soon
// as we add another camera. This includes indirect ways of adding cameras like using
// [ui node outlines](https://bevyengine.org/news/bevy-0-14/#ui-node-outline-gizmos)
// for debugging. So it's good to have this here for future-proofing.
IsDefaultUiCamera,
))
.insert(ParallaxCameraComponent::default()) //TODO:bevy-parallax plugin need to be updated
.id();

// Setup parallax
// create_parallax.send(CreateParallaxEvent {
// layers_data: vec![
// LayerData {
// speed: LayerSpeed::Bidirectional(0.95, 0.95),
// path: "background/black.png".to_string(),
// tile_size: UVec2::new(1024, 1024),
// scale: Vec2::splat(5.0),
// z: RenderLayer::Background.as_z_with_offset(-10.),
// ..default()
// },
// LayerData {
// speed: LayerSpeed::Bidirectional(0.9, 0.9),
// path: "background/stars-tile.png".to_string(),
// tile_size: UVec2::new(1024, 1024),
// z: RenderLayer::Background.as_z(),
// ..default()
// },
// ],
// camera,
// });
create_parallax.send(CreateParallaxEvent {
layers_data: vec![
LayerData {
speed: LayerSpeed::Bidirectional(0.95, 0.95),
path: "background/black.png".to_string(),
tile_size: UVec2::new(1024, 1024),
scale: Vec2::splat(5.0),
z: RenderLayer::Background.as_z_with_offset(-10.),
..default()
},
LayerData {
speed: LayerSpeed::Bidirectional(0.9, 0.9),
path: "background/stars-tile.png".to_string(),
tile_size: UVec2::new(1024, 1024),
z: RenderLayer::Background.as_z(),
..default()
},
],
camera,
});

// Spawn a shape so that the shape loop always runs (fixes bug with library cleaning itself up)
// commands.spawn((ShapeBundle {
// path: GeometryBuilder::build_as(&shapes::Line(Vec2::ZERO, Vec2::ZERO)),
// ..default()
// },));
commands.spawn((ShapeBundle {
path: GeometryBuilder::build_as(&shapes::Line(Vec2::ZERO, Vec2::ZERO)),
..default()
},));
}
14 changes: 7 additions & 7 deletions src/util/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ pub enum RenderLayer {
impl RenderLayer {
/// Gets named z position with offset to stay in allocated range.
/// The offset must be from -100 to 100 (exclusive) or the app will panic.
// pub fn as_z_with_offset(self, offset: f32) -> f32 {
// if offset >= 100.0 || offset <= -100.0 {
// panic!("Layer offset can not be 100 or more");
// }
// let base = self as u16 as f32;
// base + offset
// }
pub fn as_z_with_offset(self, offset: f32) -> f32 {
if offset >= 100.0 || offset <= -100.0 {
panic!("Layer offset can not be 100 or more");
}
let base = self as u16 as f32;
base + offset
}

pub const fn as_z(self) -> f32 {
self as u16 as f32
Expand Down

0 comments on commit fb8acdf

Please sign in to comment.