@@ -2,20 +2,54 @@ use crate::camera::*;
2
2
use bevy:: prelude:: * ;
3
3
use bevy_mod_raycast:: prelude:: * ;
4
4
5
- pub fn handle_block_breaking (
5
+ // Helper function to snap a Vec3 position to the grid
6
+ fn snap_to_grid ( position : Vec3 ) -> Vec3 {
7
+ Vec3 :: new ( position. x . round ( ) , position. y . round ( ) , position. z . round ( ) )
8
+ }
9
+
10
+ // Function to handle block placement and breaking
11
+ pub fn handle_block_interactions (
6
12
mut commands : Commands ,
7
- mouse_input : Res < ButtonInput < MouseButton > > , // to handle mouse input
13
+ mouse_input : Res < ButtonInput < MouseButton > > , // to handle mouse input
14
+ mut meshes : ResMut < Assets < Mesh > > , // for adding new block meshes
15
+ mut materials : ResMut < Assets < StandardMaterial > > , // for adding new block materials
8
16
raycast_source : Query < & RaycastSource < BlockRaycastSet > > , // raycast from the camera
9
17
) {
10
- // check if the left mouse button was pressed
11
- if mouse_input. just_pressed ( MouseButton :: Left ) {
12
- let raycast_source = raycast_source. single ( ) ;
18
+ let dirt_material = materials. add ( Color :: srgb ( 0.5 , 0.25 , 0.0 ) ) ; // Material for dirt block
19
+ let cube_mesh = meshes. add ( Mesh :: from ( Cuboid :: new ( 1.0 , 1.0 , 1.0 ) ) ) ; // Cube mesh for the blocks
13
20
14
- // check if there are any intersections with a block
21
+ let raycast_source = raycast_source. single ( ) ;
22
+
23
+ // Handle left-click for breaking blocks
24
+ if mouse_input. just_pressed ( MouseButton :: Left ) {
25
+ // Check if there are any intersections with a block
15
26
if let Some ( ( entity, _intersection) ) = raycast_source. intersections ( ) . first ( ) {
16
- // println!("block hit, removing...");
17
- // remove the hit block
27
+ // Remove the hit block
18
28
commands. entity ( * entity) . despawn ( ) ;
19
29
}
20
30
}
31
+
32
+ // Handle right-click for placing blocks
33
+ if mouse_input. just_pressed ( MouseButton :: Right ) {
34
+ if let Some ( ( _entity, intersection) ) = raycast_source. intersections ( ) . first ( ) {
35
+ // Get the normal of the face where the block will be placed
36
+ let normal = intersection. normal ( ) ; // This is already a Vec3, no need to unwrap
37
+ // Calculate the block position by adding a small offset to the intersection point
38
+ let mut position = intersection. position ( ) + normal * 0.51 ;
39
+
40
+ // Snap the position to the grid
41
+ position = snap_to_grid ( position) ;
42
+
43
+ // Spawn a new dirt block at the snapped position
44
+ commands. spawn ( (
45
+ PbrBundle {
46
+ mesh : cube_mesh. clone ( ) ,
47
+ material : dirt_material. clone ( ) ,
48
+ transform : Transform :: from_translation ( position) ,
49
+ ..Default :: default ( )
50
+ } ,
51
+ RaycastMesh :: < BlockRaycastSet > :: default ( ) , // Mark the new block as raycastable
52
+ ) ) ;
53
+ }
54
+ }
21
55
}
0 commit comments