Created
September 18, 2023 22:15
-
-
Save ethereumdegen/69c476d72053400feae37e88ca21fbd4 to your computer and use it in GitHub Desktop.
Bevy_Mesh_Terrain Collider Spawning Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You can use a system like this in your own code to spawn colliders for the terrain chunks | |
This example uses bevy xpbd 3d Colliders | |
This will loop through all built chunks and replace their ChunkCollisionData component with your own Collider component for whatever physics engine you are using | |
*/ | |
pub fn build_colliders_for_terrain_chunks( | |
mut commands:Commands, | |
mut chunk_query: Query<(Entity, &mut Chunk, &ChunkCollisionData, &Transform), Without<Collider>> , | |
){ | |
for (chunk_entity, chunk, chunk_collision_data, transform) in chunk_query.iter_mut(){ | |
//should match terrain config | |
let terrain_height_scale_y = 0.004; | |
let terrain_dimension_width = 1024.0 as u32; | |
let chunk_rows = 16; | |
let chunk_width = terrain_dimension_width / chunk_rows; | |
let scale = Vec3::new(chunk_width as f32,terrain_height_scale_y, chunk_width as f32); | |
let subheightmap = &chunk_collision_data.heightmap; | |
let heights_raw:&Vec<Vec<u16>> = &subheightmap.height_data; | |
let heights: Vec<Vec<f32>> = heights_raw.iter() | |
.map(|row| { | |
row.iter() | |
.map(|&val| val as f32) | |
.collect() | |
}) | |
.collect(); | |
let collider = Collider::heightfield( | |
heights, | |
scale | |
); | |
let initial_position = transform.translation; | |
// println!("added chunk collider "); | |
//add our built collision heightfield and remove the other component | |
if let Some(mut entity_commands) = commands.get_entity(chunk_entity){ | |
entity_commands.insert( | |
collider | |
); | |
entity_commands.insert( | |
RigidBody::Static | |
) ; | |
/* entity_commands.insert( | |
Position::from( initial_position ) | |
);*/ | |
entity_commands.remove::< ChunkCollisionData >( ); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment