background_asset.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <jetpack_game_icons.h>
  2. #include "background_assets.h"
  3. static AssetProperties assetProperties[BG_ASSETS_MAX] = {
  4. {.width = 27, .spawn_chance = 1, .x_offset = 24, .y_offset = 36, .sprite = &I_door},
  5. {.width = 12, .spawn_chance = 6, .x_offset = 33, .y_offset = 14, .sprite = &I_air_vent}};
  6. void background_assets_tick(BackgroundAsset* const assets) {
  7. // Move assets towards the player
  8. for(int i = 0; i < BG_ASSETS_MAX; i++) {
  9. if(assets[i].visible) {
  10. assets[i].point.x -= 1; // move left by 2 units
  11. if(assets[i].point.x <=
  12. -assets[i].properties->width) { // if the asset is out of screen
  13. assets[i].visible = false; // set asset x coordinate to 0 to mark it as "inactive"
  14. }
  15. }
  16. }
  17. }
  18. void spawn_random_background_asset(BackgroundAsset* const assets) {
  19. // Calculate the total spawn chances for all assets
  20. int total_spawn_chance = 0;
  21. for(int i = 0; i < BG_ASSETS_MAX; ++i) {
  22. total_spawn_chance += assetProperties[i].spawn_chance;
  23. }
  24. // Generate a random number between 0 and total_spawn_chance
  25. int random_number = rand() % total_spawn_chance;
  26. // Select the asset based on the random number
  27. int chosen_asset = -1;
  28. int accumulated_chance = 0;
  29. for(int i = 0; i < BG_ASSETS_MAX; ++i) {
  30. accumulated_chance += assetProperties[i].spawn_chance;
  31. if(random_number < accumulated_chance) {
  32. chosen_asset = i;
  33. break;
  34. }
  35. }
  36. // If no asset is chosen, return
  37. if(chosen_asset == -1) {
  38. return;
  39. }
  40. // Look for an available slot for the chosen asset
  41. for(int i = 0; i < BG_ASSETS_MAX; ++i) {
  42. if(assets[i].visible == false) {
  43. // Spawn the asset
  44. assets[i].point.x = 127 + assetProperties[chosen_asset].x_offset;
  45. assets[i].point.y = assetProperties[chosen_asset].y_offset;
  46. assets[i].properties = &assetProperties[chosen_asset];
  47. assets[i].visible = true;
  48. break;
  49. }
  50. }
  51. }
  52. void draw_background_assets(const BackgroundAsset* assets, Canvas* const canvas, int distance) {
  53. canvas_draw_box(canvas, 0, 6, 128, 1);
  54. canvas_draw_box(canvas, 0, 56, 128, 2);
  55. // Calculate the pillar offset based on the traveled distance
  56. int pillar_offset = distance % 64;
  57. // Draw pillars
  58. for(int x = -pillar_offset; x < 128; x += 64) {
  59. canvas_draw_icon(canvas, x, 6, &I_pillar);
  60. }
  61. // Draw assets
  62. for(int i = 0; i < BG_ASSETS_MAX; ++i) {
  63. if(assets[i].visible) {
  64. canvas_set_color(canvas, ColorBlack);
  65. canvas_draw_icon(
  66. canvas, assets[i].point.x, assets[i].point.y, assets[i].properties->sprite);
  67. }
  68. }
  69. }