Skip to content

Commit

Permalink
Merge pull request #2 from rewin123/sheeps-react-barking
Browse files Browse the repository at this point in the history
bark
  • Loading branch information
rewin123 authored Dec 5, 2023
2 parents 368d52d + 77b3d45 commit a3508da
Show file tree
Hide file tree
Showing 6 changed files with 148 additions and 48 deletions.
25 changes: 3 additions & 22 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,15 @@ jobs:
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.toml') }}
- uses: dtolnay/rust-toolchain@master
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
- name: Install alsa and udev
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev
if: runner.os == 'linux'
- name: Build & run tests
run: cargo test
all-doc-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ubuntu-latest-cargo-all-doc-tests-${{ hashFiles('**/Cargo.toml') }}
- uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- name: Install alsa and udev
run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev
- name: Run doc tests with all features (this also compiles README examples)
run: cargo test --doc --all-features

lint:
runs-on: ubuntu-latest
steps:
Expand All @@ -62,7 +43,7 @@ jobs:
~/.cargo/git/db/
target/
key: ubuntu-latest-cargo-lint-${{ hashFiles('**/Cargo.toml') }}
- uses: dtolnay/rust-toolchain@master
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: rustfmt, clippy
Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use bevy::prelude::*;
// This example game uses States to separate logic
// See https://bevy-cheatbook.github.io/programming/states.html
// Or https://github.com/bevyengine/bevy/blob/main/examples/ecs/state.rs
#[allow(dead_code)]
#[derive(States, Default, Clone, Eq, PartialEq, Debug, Hash)]
enum GameState {
// During the loading State the LoadingPlugin will load our assets
Expand All @@ -42,6 +43,14 @@ impl Plugin for GamePlugin {
app.add_plugins((player::PlayerPlugin, physics::PhysicsPlugin));

app.add_systems(Startup, (test_level::setup, sheep::setup));
// TODO: Move to plugin
app.add_systems(
Update,
(
sheep::scared_sheeps.before(sheep::sheep_state),
sheep::update_scared_sheeps,
),
);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/physics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ impl Plugin for PhysicsPlugin {
}
}

#[derive(Component, Default)]
#[derive(Component, Default, Reflect)]
pub struct Velocity(pub Vec3);

fn apply_velocity(mut query: Query<(&Velocity, &mut Transform)>, time: Res<Time>) {
Expand Down
42 changes: 33 additions & 9 deletions src/player.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::{prelude::*, window::PrimaryWindow, input::mouse::MouseWheel};
use bevy::{input::mouse::MouseWheel, prelude::*, window::PrimaryWindow};

use crate::{get_sprite_rotation, physics::Velocity};

Expand All @@ -16,6 +16,7 @@ pub enum MovementStyle {
impl Plugin for PlayerPlugin {
fn build(&self, app: &mut App) {
app.add_event::<SpawnPlayer>()
.add_event::<Bark>()
.add_state::<MovementStyle>()
.add_systems(Update, spawn_player_by_event)
.add_systems(
Expand All @@ -26,8 +27,8 @@ impl Plugin for PlayerPlugin {
Update,
player_movemnt_by_mouse.run_if(in_state(MovementStyle::Mouse)),
)
.add_systems(Update, (set_cam_distance, camera_movement))
.add_systems(Update, change_movement_style);
.add_systems(Update, (change_movement_style, bark))
.add_systems(Update, (set_cam_distance, camera_movement));
}
}

Expand Down Expand Up @@ -59,6 +60,12 @@ pub struct SpawnPlayer {
pub position: Vec3,
}

#[derive(Event)]
pub struct Bark {
pub radius: f32,
pub position: Vec3,
}

fn spawn_player_by_event(
mut commands: Commands,
mut event_reader: EventReader<SpawnPlayer>,
Expand Down Expand Up @@ -130,7 +137,7 @@ fn player_movemnt_by_mouse(

let dir = (globel_cursor - transform.translation).normalize_or_zero();

let max_speed = speed.min(((globel_cursor - transform.translation).length() * 10.0) as f32);
let max_speed = speed.min((globel_cursor - transform.translation).length() * 10.0);
let target_speed = (dir * speed).clamp_length(0.0, max_speed);

let dspeed = target_speed - vel.0;
Expand All @@ -140,6 +147,23 @@ fn player_movemnt_by_mouse(
vel.0 = vel.0.clamp_length_max(speed);
}

pub fn bark(
player_query: Query<&Transform, With<Player>>,
input: Res<Input<KeyCode>>,
mut event_writer: EventWriter<Bark>,
) {
let Ok(bark) = player_query.get_single() else {
return;
};

if input.pressed(KeyCode::Space) {
event_writer.send(Bark {
radius: 15.,
position: bark.translation,
});
}
}

fn player_movemnt_by_wasd(
mut player_query: Query<&mut Velocity, With<Player>>,
input: Res<Input<KeyCode>>,
Expand Down Expand Up @@ -186,7 +210,7 @@ fn player_movemnt_by_wasd(
fn camera_movement(
mut camera_query: Query<(&mut Transform, &mut CameraDistance), With<Camera>>,
player_query: Query<&Transform, (With<Player>, Without<Camera>)>,
time : Res<Time>,
time: Res<Time>,
mut scroll_evr: EventReader<MouseWheel>,
) {
let Ok((mut camera, mut distance)) = camera_query.get_single_mut() else {
Expand Down Expand Up @@ -218,10 +242,10 @@ fn camera_movement(

fn set_cam_distance(
mut commands: Commands,
camera_without_dist : Query<(Entity, &Transform), (With<Camera>, Without<CameraDistance>)>,
player_query: Query<&Transform, With<Player>>
camera_without_dist: Query<(Entity, &Transform), (With<Camera>, Without<CameraDistance>)>,
player_query: Query<&Transform, With<Player>>,
) {
let Ok( player) = player_query.get_single() else {
let Ok(player) = player_query.get_single() else {
return;
};

Expand All @@ -232,4 +256,4 @@ fn set_cam_distance(
let dist = (player.translation - camera.translation).dot(camera.forward());

commands.entity(e).insert(CameraDistance(dist));
}
}
114 changes: 101 additions & 13 deletions src/sheep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,90 @@ use std::f32::consts::PI;
use bevy::prelude::*;
use rand::Rng;

use crate::{physics::Velocity, player::Bark};

const SHEEP_PATH: &str = "test/sheep.png";

#[derive(Default, PartialEq, Eq, Debug, Clone, Component, Reflect)]
pub struct Sheep;

#[derive(Default, PartialEq, Debug, Clone, Component, Reflect)]
pub struct IsScared(bool, f32);

#[derive(Default, PartialEq, Eq, Debug, Clone, Component, Reflect)]
#[reflect(Component, Default)]
pub enum Decision {
#[default]
Idle,
Feed,
MoveToSafeZone,
MoveOutSafeZone,
}

#[derive(PartialEq, Debug, Clone, Resource, Reflect)]
#[reflect(Resource, Default)]
pub struct StateChance {
next_state: Vec<(f32, Decision)>,
}

impl Default for StateChance {
fn default() -> Self {
Self {
next_state: vec![
(0.25, Decision::Idle),
(0.5, Decision::Feed),
(0.75, Decision::MoveToSafeZone),
(1.0, Decision::MoveOutSafeZone),
],
}
}
}

pub fn scared_sheeps(
mut event_reader: EventReader<Bark>,
mut sheeps: Query<(&Sheep, &Transform, &mut Velocity, &mut IsScared)>,
) {
if let Some(bark) = event_reader.read().next() {
let bark_origin = bark.position;
for mut sheep in &mut sheeps {
if sheep.1.translation.distance(bark_origin) <= bark.radius {
sheep.3 .0 = true;
sheep.2 .0 = sheep.1.translation - bark_origin;
}
}
}
event_reader.clear();
}

pub fn sheep_state(
_next_state: Res<StateChance>,
mut sheeps: Query<(&Sheep, &mut Velocity, &mut Decision, &IsScared)>,
) {
for mut sheep in &mut sheeps.iter_mut().filter(|query| !query.3 .0) {
*sheep.2 = Decision::Feed;
*sheep.1 = Velocity(Vec3 {
x: 3.,
y: 3.,
z: 3.,
});
}
}

pub fn update_scared_sheeps(
time: Res<Time>,
mut sheeps: Query<(&Sheep, &mut Velocity, &mut Decision, &mut IsScared)>,
) {
for mut sheep in sheeps.iter_mut().filter(|q| q.3 .0) {
if sheep.3 .1 > 2. {
*sheep.2 = Decision::Idle;
*sheep.1 = Velocity::default();
*sheep.3 = IsScared::default();
} else {
sheep.3 .1 += time.delta_seconds();
}
}
}

pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
Expand Down Expand Up @@ -41,18 +123,24 @@ pub fn setup(
continue;
}

commands.spawn(PbrBundle {
mesh: square.clone(),
material: sheep_material.clone(),
transform: Transform::from_xyz(pos.x, pos.y + 3.0, pos.z)
.with_rotation(Quat::from_euler(
EulerRot::XYZ,
PI / 2.0 - PI / 4.0,
0.0,
0.0,
))
.with_scale(Vec3::splat(10.0)),
..default()
});
commands.spawn((
PbrBundle {
mesh: square.clone(),
material: sheep_material.clone(),
transform: Transform::from_xyz(pos.x, pos.y + 3.0, pos.z)
.with_rotation(Quat::from_euler(
EulerRot::XYZ,
PI / 2.0 - PI / 4.0,
0.0,
0.0,
))
.with_scale(Vec3::splat(10.0)),
..default()
},
Sheep,
Decision::Idle,
Velocity::default(),
IsScared(false, 0.),
));
}
}
4 changes: 1 addition & 3 deletions src/test_level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ pub fn setup(
});

//spawn sun
let mut cascades = CascadeShadowConfigBuilder::default();
cascades.maximum_distance = 1000.0;
cascades.minimum_distance = 1.0;
let cascades = CascadeShadowConfigBuilder::default();
commands.spawn(DirectionalLightBundle {
transform: Transform::from_xyz(100.0, 100.0, 100.0).looking_at(Vec3::ZERO, Vec3::Y),
directional_light: DirectionalLight {
Expand Down

0 comments on commit a3508da

Please sign in to comment.