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

Question: How to spawn a simple cube #28

Open
Occuros opened this issue Mar 16, 2023 · 0 comments
Open

Question: How to spawn a simple cube #28

Occuros opened this issue Mar 16, 2023 · 0 comments

Comments

@Occuros
Copy link

Occuros commented Mar 16, 2023

Bevy provides simple shapes to whitebox a level or to create simple gameplay prototypes.

Ideally I would like to use bevy_proto to define the locations and shapes for faster iterations, especially for colliders for rapier etc., but when I try to get the handle of the created mesh, it panicks.

Here is what I tried to do:

#[derive(Serialize, Deserialize)]
pub struct ShapeDef {
    pub size: f32,
    pub color: Color,
    pub position: Vec3,
    #[serde(skip)]
    pub mesh_handle:  RwLock<Option<Handle<Mesh>>>,
    #[serde(skip)]
    pub material_handle: RwLock<Option<Handle<StandardMaterial>>>,
}
#[typetag::serde]
impl ProtoComponent for ShapeDef {
    fn insert_self(&self, commands: &mut ProtoCommands, asset_server: &Res<AssetServer>) {

        let mesh_handle_id = self.mesh_handle.read().unwrap().as_ref().unwrap().id();
        let mesh_handle = commands.get_handle(self, mesh_handle_id).expect("mesh handle");
        let material_id = self.material_handle.read().unwrap().as_ref().unwrap().id();
        let material_handle = commands.get_handle(self, material_id).expect("material handle");
        commands.insert(PbrBundle {
            mesh: mesh_handle,
            material: material_handle,
            transform: Transform::from_xyz(self.position.x, self.position.y, self.position.z),
            ..default()
        });
    }

    fn prepare(&self, world: &mut World, prototype: &dyn Prototypical, data: &mut ProtoData) {
        let mut meshes = world.get_resource_mut::<Assets<Mesh>>().unwrap();

        let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: self.size }));
        let mut materials = world.get_resource_mut::<Assets<StandardMaterial>>().unwrap();
        let material_handle = materials.add(Color::rgb(0.3, 0.5, 0.3).into());
        *self.mesh_handle.write().unwrap() = Some(mesh_handle);
        *self.material_handle.write().unwrap() = Some(material_handle);
    }
}

The panic happens when I try to extract the mesh_handle from the commands_get_handle().

How exactly can I pass the Handle<Mesh> from the prepare invocation to the insert_self.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant