|
| 1 | +use bevy::prelude::*; |
| 2 | +use crate::components::CoinComponent; |
| 3 | +use crate::events::coin::CoinCollisionEvent; |
| 4 | +use crate::resources::{PlayerPosition, MazeResource}; |
| 5 | +use crate::maze::Coin; |
| 6 | + |
| 7 | +/// This system checks the player's current position against all coin positions in the maze. |
| 8 | +/// If the player is on the same tile as a coin, it dispatches a `CoinCollisionEvent`. |
| 9 | +pub fn detect_coin_collision( |
| 10 | + player_pos: Res<PlayerPosition>, |
| 11 | + maze_res: Res<MazeResource>, |
| 12 | + mut event_writer: EventWriter<CoinCollisionEvent>, |
| 13 | +) { |
| 14 | + // Assuming the player moves in tile increments, cast the logical position to i32. |
| 15 | + let player_tile_x = player_pos.x as i32; |
| 16 | + let player_tile_y = player_pos.y as i32; |
| 17 | + |
| 18 | + for coin in maze_res.maze.coins.iter() { |
| 19 | + if coin.x == player_tile_x && coin.y == player_tile_y { |
| 20 | + event_writer.send(CoinCollisionEvent { |
| 21 | + coin_x: coin.x, |
| 22 | + coin_y: coin.y, |
| 23 | + }); |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/// This system listens for `CoinCollisionEvent` and removes the collided coin from the maze. |
| 29 | +pub fn remove_coin_on_collision( |
| 30 | + mut events: EventReader<CoinCollisionEvent>, |
| 31 | + mut maze_res: ResMut<MazeResource>, |
| 32 | + mut commands: Commands, |
| 33 | + query: Query<(Entity, &CoinComponent)>, |
| 34 | +) { |
| 35 | + for event in events.read() { |
| 36 | + // Remove the coin at the collision coordinates. |
| 37 | + maze_res.maze.remove_coin(Coin { x: event.coin_x, y: event.coin_y }); |
| 38 | + // Despawn coin entity with matching coordinates. |
| 39 | + for (entity, coin_comp) in query.iter() { |
| 40 | + if coin_comp.x == event.coin_x && coin_comp.y == event.coin_y { |
| 41 | + commands.entity(entity).despawn_recursive(); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments