Skip to content

Commit

Permalink
docs: refactor platformer example by topic (#329)
Browse files Browse the repository at this point in the history
The components and systems in the platformer example are confusingly
sorted: components are stored in a separate file from the systems that
use them, and within those files the components & systems are jumbled
chaotically with little rhyme or reason. In a crate example this
complex, this organization scheme makes understanding the code a real
challenge (which is a major reason I couldn't update this example in
#294).

This PR reorganizes the platformer example into modules sorted roughly
by "part of the game" or "game system" (camera system, climbing,
inventory, etc.). Each module contains both the components and ECS
systems specific to that part, to present a complete picture of what the
game system does and how it works.

No game logic has been changed. This PR focuses purely on code quality.
  • Loading branch information
Koopa1018 authored Aug 12, 2024
1 parent 4ccc97f commit f59e5e5
Show file tree
Hide file tree
Showing 13 changed files with 862 additions and 757 deletions.
71 changes: 71 additions & 0 deletions examples/platformer/camera.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;

use crate::player::Player;

const ASPECT_RATIO: f32 = 16. / 9.;

#[allow(clippy::type_complexity)]
pub fn camera_fit_inside_current_level(
mut camera_query: Query<
(
&mut bevy::render::camera::OrthographicProjection,
&mut Transform,
),
Without<Player>,
>,
player_query: Query<&Transform, With<Player>>,
level_query: Query<(&Transform, &LevelIid), (Without<OrthographicProjection>, Without<Player>)>,
ldtk_projects: Query<&Handle<LdtkProject>>,
level_selection: Res<LevelSelection>,
ldtk_project_assets: Res<Assets<LdtkProject>>,
) {
if let Ok(Transform {
translation: player_translation,
..
}) = player_query.get_single()
{
let player_translation = *player_translation;

let (mut orthographic_projection, mut camera_transform) = camera_query.single_mut();

for (level_transform, level_iid) in &level_query {
let ldtk_project = ldtk_project_assets
.get(ldtk_projects.single())
.expect("Project should be loaded if level has spawned");

let level = ldtk_project
.get_raw_level_by_iid(&level_iid.to_string())
.expect("Spawned level should exist in LDtk project");

if level_selection.is_match(&LevelIndices::default(), level) {
let level_ratio = level.px_wid as f32 / level.px_hei as f32;
orthographic_projection.viewport_origin = Vec2::ZERO;
if level_ratio > ASPECT_RATIO {
// level is wider than the screen
let height = (level.px_hei as f32 / 9.).round() * 9.;
let width = height * ASPECT_RATIO;
orthographic_projection.scaling_mode =
bevy::render::camera::ScalingMode::Fixed { width, height };
camera_transform.translation.x =
(player_translation.x - level_transform.translation.x - width / 2.)
.clamp(0., level.px_wid as f32 - width);
camera_transform.translation.y = 0.;
} else {
// level is taller than the screen
let width = (level.px_wid as f32 / 16.).round() * 16.;
let height = width / ASPECT_RATIO;
orthographic_projection.scaling_mode =
bevy::render::camera::ScalingMode::Fixed { width, height };
camera_transform.translation.y =
(player_translation.y - level_transform.translation.y - height / 2.)
.clamp(0., level.px_hei as f32 - height);
camera_transform.translation.x = 0.;
}

camera_transform.translation.x += level_transform.translation.x;
camera_transform.translation.y += level_transform.translation.y;
}
}
}
}
79 changes: 79 additions & 0 deletions examples/platformer/climbing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use bevy::{prelude::*, utils::HashSet};
use bevy_ecs_ldtk::prelude::*;
use bevy_rapier2d::prelude::*;

use crate::colliders::SensorBundle;

#[derive(Clone, Eq, PartialEq, Debug, Default, Component)]
pub struct Climber {
pub climbing: bool,
pub intersecting_climbables: HashSet<Entity>,
}

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

#[derive(Clone, Default, Bundle, LdtkIntCell)]
pub struct LadderBundle {
#[from_int_grid_cell]
pub sensor_bundle: SensorBundle,
pub climbable: Climbable,
}

pub fn detect_climb_range(
mut climbers: Query<&mut Climber>,
climbables: Query<Entity, With<Climbable>>,
mut collisions: EventReader<CollisionEvent>,
) {
for collision in collisions.read() {
match collision {
CollisionEvent::Started(collider_a, collider_b, _) => {
if let (Ok(mut climber), Ok(climbable)) =
(climbers.get_mut(*collider_a), climbables.get(*collider_b))
{
climber.intersecting_climbables.insert(climbable);
}
if let (Ok(mut climber), Ok(climbable)) =
(climbers.get_mut(*collider_b), climbables.get(*collider_a))
{
climber.intersecting_climbables.insert(climbable);
};
}
CollisionEvent::Stopped(collider_a, collider_b, _) => {
if let (Ok(mut climber), Ok(climbable)) =
(climbers.get_mut(*collider_a), climbables.get(*collider_b))
{
climber.intersecting_climbables.remove(&climbable);
}

if let (Ok(mut climber), Ok(climbable)) =
(climbers.get_mut(*collider_b), climbables.get(*collider_a))
{
climber.intersecting_climbables.remove(&climbable);
}
}
}
}
}

pub fn ignore_gravity_if_climbing(
mut query: Query<(&Climber, &mut GravityScale), Changed<Climber>>,
) {
for (climber, mut gravity_scale) in &mut query {
if climber.climbing {
gravity_scale.0 = 0.0;
} else {
gravity_scale.0 = 1.0;
}
}
}

pub struct ClimbingPlugin;

impl Plugin for ClimbingPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, detect_climb_range)
.add_systems(Update, ignore_gravity_if_climbing)
.register_ldtk_int_cell::<LadderBundle>(2);
}
}
76 changes: 76 additions & 0 deletions examples/platformer/colliders.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use bevy::prelude::*;
use bevy_ecs_ldtk::prelude::*;

use bevy_rapier2d::prelude::*;

#[derive(Clone, Default, Bundle, LdtkIntCell)]
pub struct ColliderBundle {
pub collider: Collider,
pub rigid_body: RigidBody,
pub velocity: Velocity,
pub rotation_constraints: LockedAxes,
pub gravity_scale: GravityScale,
pub friction: Friction,
pub density: ColliderMassProperties,
}

impl From<&EntityInstance> for ColliderBundle {
fn from(entity_instance: &EntityInstance) -> ColliderBundle {
let rotation_constraints = LockedAxes::ROTATION_LOCKED;

match entity_instance.identifier.as_ref() {
"Player" => ColliderBundle {
collider: Collider::cuboid(6., 14.),
rigid_body: RigidBody::Dynamic,
friction: Friction {
coefficient: 0.0,
combine_rule: CoefficientCombineRule::Min,
},
rotation_constraints,
..Default::default()
},
"Mob" => ColliderBundle {
collider: Collider::cuboid(5., 5.),
rigid_body: RigidBody::KinematicVelocityBased,
rotation_constraints,
..Default::default()
},
"Chest" => ColliderBundle {
collider: Collider::cuboid(8., 8.),
rigid_body: RigidBody::Dynamic,
rotation_constraints,
gravity_scale: GravityScale(1.0),
friction: Friction::new(0.5),
density: ColliderMassProperties::Density(15.0),
..Default::default()
},
_ => ColliderBundle::default(),
}
}
}

#[derive(Clone, Default, Bundle, LdtkIntCell)]
pub struct SensorBundle {
pub collider: Collider,
pub sensor: Sensor,
pub active_events: ActiveEvents,
pub rotation_constraints: LockedAxes,
}

impl From<IntGridCell> for SensorBundle {
fn from(int_grid_cell: IntGridCell) -> SensorBundle {
let rotation_constraints = LockedAxes::ROTATION_LOCKED;

// ladder
if int_grid_cell.value == 2 {
SensorBundle {
collider: Collider::cuboid(8., 8.),
sensor: Sensor,
rotation_constraints,
active_events: ActiveEvents::COLLISION_EVENTS,
}
} else {
SensorBundle::default()
}
}
}
Loading

0 comments on commit f59e5e5

Please sign in to comment.