bevyjam/src/game.rs

508 lines
13 KiB
Rust
Raw Normal View History

2022-08-21 17:53:08 +00:00
#![allow(clippy::precedence)]
2022-08-22 18:03:19 +00:00
#![allow(clippy::too_many_arguments)]
2022-08-21 17:53:08 +00:00
2022-08-24 10:21:08 +00:00
pub use crate::filters::*;
2022-08-21 17:17:55 +00:00
use crate::AppState;
use bevy::{
2022-08-24 16:51:18 +00:00
ecs::system::EntityCommands,
2022-08-21 17:17:55 +00:00
input::{keyboard::KeyCode, Input},
prelude::{shape::Quad, *},
2022-08-24 16:51:18 +00:00
sprite::Mesh2dHandle,
2022-08-21 17:17:55 +00:00
};
use bevy_rapier2d::prelude::*;
2022-08-24 21:11:59 +00:00
use rapier2d::geometry::CollisionEventFlags;
2022-08-21 17:17:55 +00:00
2022-08-24 09:31:17 +00:00
pub enum AudioMsg {
Color([f32; 3]),
2022-08-24 12:51:49 +00:00
Fusion,
2022-08-24 09:31:17 +00:00
Jump,
2022-08-24 12:51:49 +00:00
Switch,
2022-08-24 09:31:17 +00:00
}
2022-08-23 10:02:58 +00:00
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct LevelId(pub u32);
2022-08-21 17:17:55 +00:00
pub struct GamePlugin;
impl Plugin for GamePlugin {
fn build(&self, app: &mut App) {
app.add_event::<LevelStartupEvent>()
.init_resource::<CharacterMeshes>()
.insert_resource(CurrentLevel(None))
.add_system_set(SystemSet::on_enter(AppState::Game).with_system(setup))
2022-08-23 10:02:58 +00:00
.add_system_set(SystemSet::on_enter(AppState::Win).with_system(win_setup))
.add_system_set(
SystemSet::on_exit(AppState::Win).with_system(crate::levels::despawn_level),
)
2022-08-21 17:17:55 +00:00
.add_system_set(
SystemSet::on_update(AppState::Game)
2022-08-23 10:02:58 +00:00
.with_system(crate::levels::post_setup_level)
.with_system(change_character_system)
.with_system(player_movement_system)
2022-08-25 09:31:12 +00:00
.with_system(level_keyboard_system)
2022-08-24 07:58:56 +00:00
.with_system(move_camera)
.with_system(character_particle_effect_system),
2022-08-24 16:51:18 +00:00
)
.add_system_set(
SystemSet::on_update(AppState::Win)
.with_system(player_movement_system)
2022-08-25 09:31:12 +00:00
.with_system(level_keyboard_system)
2022-08-24 07:58:56 +00:00
.with_system(move_camera)
.with_system(character_particle_effect_system),
2022-08-21 17:17:55 +00:00
)
.add_system_to_stage(CoreStage::PostUpdate, collision_event_system);
}
}
// Events
2022-08-25 09:31:12 +00:00
pub struct LevelStartupEvent;
2022-08-21 17:17:55 +00:00
// Resources
2022-08-23 10:02:58 +00:00
pub struct CurrentLevel(pub Option<LevelId>);
2022-08-21 17:17:55 +00:00
2022-08-23 10:02:58 +00:00
pub struct CharacterMeshes {
2022-08-21 17:17:55 +00:00
square: Mesh2dHandle,
}
impl FromWorld for CharacterMeshes {
fn from_world(world: &mut World) -> Self {
let mut meshes = world.get_resource_mut::<Assets<Mesh>>().unwrap();
Self {
square: meshes
.add(Mesh::from(Quad {
size: Vec2 { x: 64.0, y: 64.0 },
flip: false,
}))
.into(),
}
}
}
// Components
2022-08-23 10:02:58 +00:00
#[derive(Component)]
pub struct Level;
2022-08-21 17:17:55 +00:00
2022-08-22 21:34:54 +00:00
#[derive(Clone, Component, PartialEq)]
2022-08-23 10:02:58 +00:00
pub struct CharacterColor(pub Color);
2022-08-22 21:34:54 +00:00
#[derive(Component)]
pub struct Player;
2022-08-25 12:47:20 +00:00
#[derive(Component)]
pub struct CollisionCount(usize);
2022-08-21 17:17:55 +00:00
// Systems
fn setup(
mut current_level: ResMut<CurrentLevel>,
mut level_startup_event: EventWriter<LevelStartupEvent>,
2022-08-23 22:45:57 +00:00
mut camera_query: Query<&mut Transform, With<Camera>>,
2022-08-21 17:17:55 +00:00
) {
2022-08-25 09:31:12 +00:00
if current_level.0.is_none() {
current_level.0 = Some(LevelId(0));
}
crate::levels::setup_level(&mut level_startup_event, &mut camera_query);
2022-08-21 17:17:55 +00:00
}
2022-08-24 16:51:18 +00:00
pub fn spawn_characters<I: IntoIterator<Item = (Transform, Color)>>(
commands: &mut Commands,
character_meshes: &Res<CharacterMeshes>,
materials: &mut ResMut<Assets<ColorMaterial>>,
audio: &Res<crossbeam_channel::Sender<AudioMsg>>,
2022-08-24 16:51:18 +00:00
characters: I,
) {
2022-08-24 16:51:18 +00:00
for (i, (transform, color)) in characters.into_iter().enumerate() {
spawn_character(
commands,
character_meshes,
materials,
audio,
2022-08-24 16:51:18 +00:00
transform,
color,
i == 0,
);
}
}
2022-08-23 10:02:58 +00:00
pub fn spawn_character(
2022-08-21 17:17:55 +00:00
commands: &mut Commands,
character_meshes: &Res<CharacterMeshes>,
2022-08-21 21:46:07 +00:00
materials: &mut ResMut<Assets<ColorMaterial>>,
2022-08-23 15:02:13 +00:00
audio: &Res<crossbeam_channel::Sender<AudioMsg>>,
mut transform: Transform,
2022-08-21 21:46:07 +00:00
color: Color,
is_player: bool,
2022-08-21 17:17:55 +00:00
) {
transform.translation.z = transform.translation.z.max(1.0);
let color_mesh_2d_bundle: ColorMesh2dBundle = ColorMesh2dBundle {
mesh: character_meshes.square.clone(),
material: materials.add(ColorMaterial::from(color)),
transform,
..default()
};
2022-08-21 17:17:55 +00:00
let mut entity_commands: EntityCommands = commands.spawn_bundle(color_mesh_2d_bundle);
entity_commands
2022-08-23 10:02:58 +00:00
.insert(Level)
2022-08-22 21:34:54 +00:00
.insert(CharacterColor(color))
2022-08-21 17:17:55 +00:00
.insert(RigidBody::Dynamic)
.insert(Collider::cuboid(32., 32.))
2022-08-22 16:56:11 +00:00
.insert(Velocity::default())
.insert(GravityScale(10.0))
.insert(LockedAxes::ROTATION_LOCKED)
2022-08-22 18:03:19 +00:00
.insert(Friction::new(0.8))
2022-08-21 17:17:55 +00:00
.insert(Damping {
linear_damping: 0.5,
angular_damping: 0.5,
})
2022-08-25 12:47:20 +00:00
.insert(ActiveEvents::COLLISION_EVENTS)
.with_children(|c| {
c.spawn_bundle(TransformBundle::from_transform(Transform::from_xyz(
0., -33., 0.,
)))
.insert(Sensor)
.insert(Collider::cuboid(30., 0.5))
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(CollisionCount(0));
});
2022-08-21 17:17:55 +00:00
if is_player {
entity_commands.insert(Player);
2022-08-23 15:02:13 +00:00
audio
.send(AudioMsg::Color([color.r(), color.g(), color.b()]))
.ok();
2022-08-21 17:17:55 +00:00
}
}
2022-08-25 10:32:06 +00:00
pub fn spawn_platforms<I: IntoIterator<Item = (Transform, Vec2)>>(
commands: &mut Commands,
meshes: &mut ResMut<Assets<Mesh>>,
materials: &mut ResMut<Assets<ColorMaterial>>,
platforms: I,
) {
for (transform, size) in platforms.into_iter() {
spawn_platform(commands, meshes, materials, transform, size);
}
}
pub fn spawn_platform(
commands: &mut Commands,
meshes: &mut ResMut<Assets<Mesh>>,
materials: &mut ResMut<Assets<ColorMaterial>>,
transform: Transform,
size: Vec2,
) {
commands
.spawn_bundle(ColorMesh2dBundle {
mesh: meshes.add(Mesh::from(Quad { size, flip: false })).into(),
material: materials.add(ColorMaterial::from(Color::GRAY)),
transform,
..default()
})
.insert(Collider::cuboid(size.x / 2., size.y / 2.))
.insert(Level);
}
2022-08-21 17:17:55 +00:00
fn collision_event_system(
mut commands: Commands,
2022-08-22 21:34:54 +00:00
character_meshes: Res<CharacterMeshes>,
mut materials: ResMut<Assets<ColorMaterial>>,
2022-08-21 17:17:55 +00:00
mut collision_events: EventReader<CollisionEvent>,
2022-08-24 21:11:59 +00:00
mut character_query: Query<(
&mut CharacterColor,
&Transform,
&mut Handle<ColorMaterial>,
Option<&Player>,
)>,
2022-08-25 07:30:47 +00:00
pass_through_filter_query: Query<&PassThroughFilter>,
2022-08-25 12:47:20 +00:00
mut collision_counter_query: Query<&mut CollisionCount>,
2022-08-23 10:02:58 +00:00
mut app_state: ResMut<State<AppState>>,
2022-08-23 15:02:13 +00:00
audio: Res<crossbeam_channel::Sender<AudioMsg>>,
2022-08-21 17:17:55 +00:00
) {
2022-08-23 10:02:58 +00:00
for collision_event in collision_events.iter() {
2022-08-25 12:47:20 +00:00
match collision_event {
CollisionEvent::Started(e1, e2, flags) => {
if flags.is_empty() {
if let (
Ok((c1_color, c1_transform, _c1_material, c1_player)),
Ok((c2_color, c2_transform, _c2_material, c2_player)),
) = (character_query.get(*e1), character_query.get(*e2))
2022-08-21 17:17:55 +00:00
{
2022-08-25 12:47:20 +00:00
commands.entity(*e1).despawn_recursive();
commands.entity(*e2).despawn_recursive();
let new_color = (Vec4::from(c1_color.0) + Vec4::from(c2_color.0))
.clamp(Vec4::ZERO, Vec4::ONE);
// If color approximately white
if app_state.current() == &AppState::Game
&& 4. - new_color.length_squared() < 0.1
{
app_state.replace(AppState::Win).ok();
}
// position character based on current player location
spawn_character(
&mut commands,
&character_meshes,
&mut materials,
&audio,
if c1_player.is_some() {
*c1_transform
} else if c2_player.is_some() {
*c2_transform
} else {
Transform::identity().with_translation(
(c1_transform.translation + c2_transform.translation) / 2.,
)
},
new_color.into(),
c1_player.is_some() || c2_player.is_some(),
);
audio.send(AudioMsg::Fusion).ok();
}
} else if *flags == CollisionEventFlags::SENSOR {
if let (Ok((mut c_color, _c_transform, mut c_material, c_player)), Ok(filter)) = (
character_query.get_mut(*e1),
pass_through_filter_query.get(*e2),
) {
c_color.0 = filter.apply(c_color.0);
*c_material = materials.add(ColorMaterial::from(c_color.0));
2022-08-25 13:39:16 +00:00
if c_player.is_some() {
audio
.send(AudioMsg::Color([
c_color.0.r(),
c_color.0.g(),
c_color.0.b(),
]))
.ok();
}
} else if let (
Ok((mut c_color, _c_transform, mut c_material, c_player)),
Ok(filter),
) = (
character_query.get_mut(*e2),
pass_through_filter_query.get(*e1),
) {
c_color.0 = filter.apply(c_color.0);
*c_material = materials.add(ColorMaterial::from(c_color.0));
2022-08-25 12:47:20 +00:00
if c_player.is_some() {
audio
.send(AudioMsg::Color([
c_color.0.r(),
c_color.0.g(),
c_color.0.b(),
]))
.ok();
}
} else if let (Ok(mut collision_count), Err(_)) = (
collision_counter_query.get_mut(*e1),
character_query.get_mut(*e2),
) {
collision_count.0 += 1;
} else if let (Ok(mut collision_count), Err(_)) = (
collision_counter_query.get_mut(*e2),
character_query.get_mut(*e1),
) {
collision_count.0 += 1;
2022-08-21 17:17:55 +00:00
}
}
2022-08-25 12:47:20 +00:00
}
CollisionEvent::Stopped(e1, e2, flags) => {
if *flags == CollisionEventFlags::SENSOR {
if let (Ok(mut collision_count), Err(_)) = (
collision_counter_query.get_mut(*e1),
character_query.get_mut(*e2),
) {
collision_count.0 = collision_count.0.saturating_sub(1);
} else if let (Ok(mut collision_count), Err(_)) = (
collision_counter_query.get_mut(*e2),
character_query.get_mut(*e1),
) {
collision_count.0 = collision_count.0.saturating_sub(1);
2022-08-24 21:11:59 +00:00
}
}
2022-08-21 17:17:55 +00:00
}
}
}
}
fn change_character_system(
mut commands: Commands,
2022-08-21 17:17:55 +00:00
keyboard_input: Res<Input<KeyCode>>,
characters: Query<(Entity, &CharacterColor, Option<&Player>)>,
2022-08-23 15:02:13 +00:00
audio: Res<crossbeam_channel::Sender<AudioMsg>>,
2022-08-21 17:17:55 +00:00
) {
2022-08-24 16:51:18 +00:00
if !keyboard_input.just_pressed(KeyCode::Tab) {
return;
}
2022-08-24 16:51:18 +00:00
let mut player_idx: usize = 0;
let mut player_count: usize = 0;
// find player idx
for (_entity, _color, player) in characters.iter() {
2022-08-24 16:51:18 +00:00
if player.is_some() {
player_idx = player_count;
2022-08-23 10:02:58 +00:00
}
player_count += 1;
}
2022-08-22 16:56:11 +00:00
// calculate next player index
let next_player_idx = (player_idx + 1) % player_count;
player_count = 0;
// exchange `Player` component from old `player_idx` to new `next_player_idx`
for (entity, color, _player) in characters.iter() {
if player_count == player_idx {
commands.entity(entity).remove::<Player>();
2022-08-21 17:17:55 +00:00
}
if player_count == next_player_idx {
commands.entity(entity).insert(Player);
audio
.send(AudioMsg::Color([color.0.r(), color.0.g(), color.0.b()]))
.ok();
2022-08-24 16:51:18 +00:00
audio.send(AudioMsg::Switch).ok();
}
player_count += 1;
2022-08-21 17:17:55 +00:00
}
}
fn player_movement_system(
keyboard_input: Res<Input<KeyCode>>,
2022-08-25 12:47:20 +00:00
mut characters: Query<(&mut Velocity, &Children), With<Player>>,
collision_counter_query: Query<&CollisionCount>,
audio: Res<crossbeam_channel::Sender<AudioMsg>>,
) {
2022-08-24 16:51:18 +00:00
let right_pressed: bool =
keyboard_input.pressed(KeyCode::Right) || keyboard_input.pressed(KeyCode::D);
let left_pressed: bool =
keyboard_input.pressed(KeyCode::Left) || keyboard_input.pressed(KeyCode::A);
2022-08-25 12:47:20 +00:00
for (mut velocity, children) in characters.iter_mut() {
2022-08-24 16:51:18 +00:00
velocity.linvel.x = 200. * (right_pressed as i8 - left_pressed as i8) as f32;
2022-08-25 12:47:20 +00:00
if keyboard_input.just_pressed(KeyCode::Space)
&& collision_counter_query.get(children[0]).unwrap().0 != 0
{
2022-08-24 16:51:18 +00:00
audio.send(AudioMsg::Jump).ok();
2022-08-25 12:47:20 +00:00
velocity.linvel.y = 700.;
2022-08-24 16:51:18 +00:00
}
}
2022-08-23 10:02:58 +00:00
}
fn character_particle_effect_system(
2022-08-24 21:11:59 +00:00
player_character: Query<(&Transform, &CharacterColor), With<Player>>,
2022-08-24 07:58:56 +00:00
mut particle_effect: ResMut<crate::particle_effect::ParticleEffectResource>,
) {
2022-08-24 21:11:59 +00:00
if let Ok((transform, color)) = player_character.get_single() {
particle_effect.translation = transform.translation;
particle_effect.color = color.0;
}
}
2022-08-25 10:32:06 +00:00
fn win_setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
asset_server: Res<AssetServer>,
) {
2022-08-23 10:42:56 +00:00
let font = asset_server.get_handle("UacariLegacy-Thin.ttf");
2022-08-25 10:32:06 +00:00
commands
.spawn_bundle(ColorMesh2dBundle {
mesh: meshes
.add(Mesh::from(Quad {
size: Vec2 { x: 512., y: 64. },
flip: false,
}))
.into(),
material: materials.add(ColorMaterial::from(Color::rgba(0., 0., 0., 0.9))),
transform: Transform::from_xyz(0., 0., 3.),
..default()
})
.insert(Level);
2022-08-23 10:42:56 +00:00
commands
.spawn_bundle(Text2dBundle {
text: Text::from_section(
"Press ENTER to level up",
TextStyle {
font,
2022-08-25 13:39:16 +00:00
font_size: 36.0,
2022-08-23 10:42:56 +00:00
color: Color::WHITE,
},
)
.with_alignment(TextAlignment::CENTER),
2022-08-25 10:32:06 +00:00
transform: Transform::from_xyz(0., 0., 4.),
2022-08-23 10:42:56 +00:00
..Default::default()
})
.insert(Level);
2022-08-21 17:17:55 +00:00
}
2022-08-23 22:45:57 +00:00
fn move_camera(
2022-08-24 08:47:09 +00:00
mut camera_query: Query<(&Camera, &mut Transform)>,
characters: Query<&Transform, (Without<Camera>, With<Player>)>,
2022-08-24 08:47:09 +00:00
time: Res<Time>,
2022-08-23 22:45:57 +00:00
) {
2022-08-24 08:47:09 +00:00
const MARGIN: f32 = 300.0;
const FOLLOW_SPEED: f32 = std::f32::consts::PI;
2022-08-23 22:45:57 +00:00
for character_transform in characters.iter() {
2022-08-24 16:51:18 +00:00
let (camera, mut camera_transform) = camera_query.single_mut();
let size: Vec2 = camera.logical_viewport_size().unwrap();
let half_height: f32 = size.y * 0.5;
camera_transform.translation = camera_transform.translation.lerp(
2022-08-24 16:51:18 +00:00
character_transform.translation,
time.delta_seconds() * FOLLOW_SPEED,
);
// prevent camera from going too low
2022-08-24 16:51:18 +00:00
camera_transform.translation.y = camera_transform.translation.y.max(half_height - MARGIN);
// always make sure that camera is away from the object in order to render them
camera_transform.translation.z = 999.0;
2022-08-23 22:45:57 +00:00
}
}
2022-08-25 09:31:12 +00:00
fn level_keyboard_system(
mut commands: Commands,
mut current_level: ResMut<CurrentLevel>,
mut level_startup_event: EventWriter<LevelStartupEvent>,
mut camera_query: Query<&mut Transform, With<Camera>>,
keyboard_input: Res<Input<KeyCode>>,
level_query: Query<Entity, With<Level>>,
mut app_state: ResMut<State<AppState>>,
) {
if app_state.current() == &AppState::Win && keyboard_input.just_pressed(KeyCode::Return) {
current_level.0 = Some(LevelId(
current_level.0.map_or(0, |level_id| level_id.0 + 1),
));
app_state.replace(AppState::Game).unwrap();
}
if keyboard_input.just_pressed(KeyCode::R) {
for entity in level_query.iter() {
commands.entity(entity).despawn_recursive();
}
if app_state.replace(AppState::Game).is_err() {
crate::levels::setup_level(&mut level_startup_event, &mut camera_query);
}
}
}