Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spawn items support #120

Merged
merged 5 commits into from
Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions assets/beach/beach.level.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,7 @@ enemies:
location: [200, -10, 0]
- fighter: *bandit
location: [250, -50, 0]

items:
- item: &bottle /items/bottle/bottle.item.yaml
location: [275, 0, 0]
5 changes: 5 additions & 0 deletions assets/items/bottle/bottle.item.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: Bottle

image:
image: bottle.png
image_size: [11, 31]
Binary file added assets/items/bottle/bottle.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
63 changes: 51 additions & 12 deletions src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub fn register(app: &mut bevy::prelude::App) {
.add_asset_loader(LevelMetaLoader)
.add_asset::<FighterMeta>()
.add_asset_loader(FighterLoader)
.add_asset::<ItemMeta>()
.add_asset_loader(ItemLoader)
.add_asset::<EguiFont>()
.add_asset_loader(EguiFontLoader);
}
Expand Down Expand Up @@ -156,24 +158,32 @@ impl AssetLoader for LevelMetaLoader {

// Load the players
for player in &mut meta.players {
let player_fighter_file_path = relative_asset_path(self_path, &player.fighter);
let player_fighter_path = AssetPath::new(player_fighter_file_path.clone(), None);
let player_fighter_handle = load_context.get_handle(player_fighter_path.clone());
let (player_fighter_path, player_fighter_handle) =
get_relative_asset(load_context, self_path, &player.fighter);
dependencies.push(player_fighter_path);

player.fighter_handle = player_fighter_handle;
}

// Load the enemies
for enemy in &mut meta.enemies {
let enemy_fighter_file_path = relative_asset_path(self_path, &enemy.fighter);
let enemy_fighter_path = AssetPath::new(enemy_fighter_file_path.clone(), None);
let enemy_fighter_handle = load_context.get_handle(enemy_fighter_path.clone());
let (enemy_fighter_path, enemy_fighter_handle) =
get_relative_asset(load_context, self_path, &enemy.fighter);
dependencies.push(enemy_fighter_path);

enemy.fighter_handle = enemy_fighter_handle;
}

// Load the items
for item in &mut meta.items {
let (item_path, item_handle) =
get_relative_asset(load_context, self_path, &item.item);

dependencies.push(item_path);

item.item_handle = item_handle;
}

// Load the music

let (music_path, music_handle) =
Expand Down Expand Up @@ -207,9 +217,8 @@ impl AssetLoader for FighterLoader {
let self_path = load_context.path();
let mut dependencies = Vec::new();

let portrait_path = relative_asset_path(self_path, &meta.hud.portrait.image);
let portrait_path = AssetPath::new(portrait_path, None);
let portrait_handle = load_context.get_handle(portrait_path.clone());
let (portrait_path, portrait_handle) =
get_relative_asset(load_context, self_path, &meta.hud.portrait.image);
dependencies.push(portrait_path);
meta.hud.portrait.image_handle = portrait_handle;

Expand All @@ -230,9 +239,8 @@ impl AssetLoader for FighterLoader {
}
}

let texture_path = relative_asset_path(self_path, &meta.spritesheet.image);
let texture_path = AssetPath::new(texture_path, None);
let texture_handle = load_context.get_handle(texture_path.clone());
let (texture_path, texture_handle) =
get_relative_asset(load_context, self_path, &meta.spritesheet.image);
let atlas_handle = load_context.set_labeled_asset(
"atlas",
LoadedAsset::new(TextureAtlas::from_grid(
Expand All @@ -256,6 +264,37 @@ impl AssetLoader for FighterLoader {
}
}

pub struct ItemLoader;

impl AssetLoader for ItemLoader {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut bevy::asset::LoadContext,
) -> bevy::utils::BoxedFuture<'a, Result<(), anyhow::Error>> {
Box::pin(async move {
let mut meta: ItemMeta = serde_yaml::from_slice(bytes)?;
trace!(?meta, "Loaded item asset");

let self_path = load_context.path();
let mut dependencies = Vec::new();

let (image_path, image_handle) =
get_relative_asset(load_context, self_path, &meta.image.image);
dependencies.push(image_path);
meta.image.image_handle = image_handle;

load_context.set_default_asset(LoadedAsset::new(meta).with_dependencies(dependencies));

Ok(())
})
}

fn extensions(&self) -> &[&str] {
&["item.yml", "item.yaml"]
}
}

#[derive(Debug, Clone, TypeUuid)]
#[uuid = "da277340-574f-4069-907c-7571b8756200"]
pub struct EguiFont(pub egui::FontData);
Expand Down
33 changes: 28 additions & 5 deletions src/item.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use bevy::{
math::Vec2,
prelude::{default, AssetServer, Commands, Component, EventReader, Res, Transform},
math::{Vec2, Vec3},
prelude::{
default, AssetServer, Bundle, Commands, Component, EventReader, Handle, Res, Transform,
},
sprite::SpriteBundle,
transform::TransformBundle,
};
use bevy_rapier2d::prelude::*;

Expand All @@ -10,14 +13,35 @@ use crate::{
attack::Attack,
collisions::BodyLayers,
consts::{self, ITEM_HEIGHT, ITEM_LAYER, ITEM_WIDTH},
metadata::{ItemMeta, ItemSpawnMeta},
movement::{MoveInArc, Rotate},
};

#[derive(Component)]
pub struct Item;

#[derive(Component)]
struct Pickable;
#[derive(Bundle)]
pub struct ItemSpawnBundle {
item_meta_handle: Handle<ItemMeta>,
#[bundle]
transform_bundle: TransformBundle,
}

impl ItemSpawnBundle {
pub fn new(item_spawn_meta: &ItemSpawnMeta) -> Self {
let item_meta_handle = item_spawn_meta.item_handle.clone();

let ground_offset = Vec3::new(0.0, consts::GROUND_Y, ITEM_LAYER);
let transform_bundle = TransformBundle::from_transform(Transform::from_translation(
item_spawn_meta.location + ground_offset,
));

Self {
item_meta_handle,
transform_bundle,
}
}
}

pub struct ThrowItemEvent {
pub position: Vec2,
Expand All @@ -42,7 +66,6 @@ pub fn spawn_throwable_items(
..default()
})
.insert(Item)
.insert(Pickable)
.insert(Collider::cuboid(ITEM_WIDTH / 2., ITEM_HEIGHT / 2.))
.insert(Sensor(true))
.insert(ActiveEvents::COLLISION_EVENTS)
Expand Down
25 changes: 24 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use audio::*;
use camera::*;
use collisions::*;
use item::{spawn_throwable_items, ThrowItemEvent};
use metadata::{FighterMeta, GameMeta, LevelMeta};
use metadata::{FighterMeta, GameMeta, ItemMeta, LevelMeta};
use movement::*;
use serde::Deserialize;
use state::{State, StatePlugin};
Expand All @@ -65,6 +65,7 @@ use crate::{
attack::{attack_cleanup, attack_tick},
config::EngineConfig,
input::PlayerAction,
item::ItemSpawnBundle,
metadata::Settings,
};

Expand Down Expand Up @@ -225,6 +226,7 @@ fn main() {
ConditionSet::new()
.run_in_state(GameState::InGame)
.with_system(load_fighters)
.with_system(load_items)
.with_system(spawn_throwable_items)
.with_system(player_controller)
.with_system(y_sort)
Expand Down Expand Up @@ -362,6 +364,11 @@ fn load_level(
commands.spawn_bundle(EnemyBundle::new(enemy));
}

// Spawn the items
for item_spawn_meta in &level.items {
commands.spawn_bundle(ItemSpawnBundle::new(item_spawn_meta));
}

commands.insert_resource(level.clone());
commands.insert_resource(NextState(GameState::InGame));
} else {
Expand Down Expand Up @@ -397,6 +404,22 @@ fn hot_reload_level(
}
}

fn load_items(
mut commands: Commands,
item_spawns: Query<(Entity, &Transform, &Handle<ItemMeta>), Without<Sprite>>,
item_assets: Res<Assets<ItemMeta>>,
) {
for (entity, transform, item_handle) in item_spawns.iter() {
if let Some(item_meta) = item_assets.get(item_handle) {
commands.entity(entity).insert_bundle(SpriteBundle {
texture: item_meta.image.image_handle.clone(),
transform: *transform,
..default()
});
}
}
}

/// Load all fighters that have their handles spawned.
///
/// Fighters are spawned as "stubs" that only contain a transform, a marker component, and a
Expand Down
20 changes: 20 additions & 0 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub struct LevelMeta {
pub players: Vec<FighterSpawnMeta>,
#[serde(default)]
pub enemies: Vec<FighterSpawnMeta>,
#[serde(default)]
pub items: Vec<ItemSpawnMeta>,
pub music: String,
#[serde(skip)]
pub music_handle: Handle<AudioSource>,
Expand All @@ -88,6 +90,14 @@ pub struct FighterMeta {
pub audio: AudioMeta,
}

#[derive(TypeUuid, Deserialize, Clone, Debug, Component)]
#[serde(deny_unknown_fields)]
#[uuid = "5e2db270-ec2e-013a-92a8-2cf05d71216b"]
pub struct ItemMeta {
pub name: String,
pub image: ImageMeta,
}

#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct FighterHudMeta {
Expand Down Expand Up @@ -124,6 +134,16 @@ pub struct FighterSpawnMeta {
pub location: Vec3,
}

#[derive(TypeUuid, Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[uuid = "f5092550-ec30-013a-92a9-2cf05d71216b"]
pub struct ItemSpawnMeta {
pub item: String,
#[serde(skip)]
pub item_handle: Handle<ItemMeta>,
pub location: Vec3,
}

#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct ParallaxMeta {
Expand Down