Spacecrash day 3 of 7: gameplay revamped
After we started to get some gameplay yesterday, let me take a bit of time and recap where we are. During the project, you have to focus and often need to work as fast as possible, but it’s important to raise your head every so often and make sure you know where you are and where you’re heading.
We are starting some gameplay out of the prototype in the current stage. It is sometimes genuinely fun to fly the ship manoeuvring between the rocks. The variety is low, but still it’s proven a bit of a challenge requiring me many attempts to reach the end of this level as posted yesterday: the end of the level is defined by the constant #define RACE_END 100000.f at the top, since each screen is 1500 units high, this means you need to fly 66 screenfuls without dying to complete it.
There are a few gameplay elements that are sure to add to the experience, at least in variety: my idea is to allow the ship to self-repair slowly by spending fuel, and I also want to add shooting rocket, extra clumps of fuel you can pick up, and also the possibility to slow down / accelerate at your own will. Apart from these gameplay elements, there are quite a few things I’m planning to add only for it to look, play and sound cool: sound effects, particle effects, nice background graphics, animations…
But let us not lose focus. All the elements above (both gameplay elements & all special effects) will not “fix” the core experience. That is something that is essential to the core gameplay. And there are some “gotchas” with the current model.
The main limitation in the current gameplay is that the totally “random” distribution of rocks creates a very uncontrolled experience. You can fly for quite a while without encountering more than random easy-to-avoid rocks, and suddenly, you can stumble into a barrier formed by several rocks which there literally isn’t any way to avoid. This is tremendously frustrating, and it totally kills the player experience. The player wants to think that this is about their skills, and it’s very important for them to know that, when they fail, it was because of a mistake of them, and that they could fix it next time.Don’t get me wrong, luck can play a role, even an important one. I have been playing plenty of Candy Crush Saga myself lately… and you can bet I think is more about luck than about anything else… but still tremendously addictive. But the point is that in CCS you still have some doubt about whether luck was the cause or not, and you can at least always play, even if you don’t beat the level! In Spacecrash, when you confront the player with a barrier of rocks without a single gap, they just feel insulted.
How can we address this? I can think of three different ways:
- Fully scripting the levels, with every rock hand-placed. This is just classic “level-design”, it would allow us the maximum level of control, and would certainly allow us to make the best game. Unfortunately we only have one week, and thus this solution is beyond our scope.
- Structuring the randomness a bit. It’s ok that it’s random, but we should be able to break the level in arbitrary sections, and manually adjust some parameters to it. We can call this “poor man’s level design”, since we will design things by hand, but only partially, adjusting several parameters. This would allow to control the “pace” of the levels, although it still wouldn’t let us fix the issue of creating “impassable barriers”.
- Adding some clever logic to the random rock generation, such that no “impassable barriers” are generated. This seems quite promising. We have to be careful not to fall in an “algorithmic black hole”: it is very common to get into trying to write some ultra-sophisticated algorithm and spend countless hours in it, without making any advance du to too much faith in algorithms. We will try to find some simple approach that works (and we can always make it more complex afterwards).
It seems to me that combining the second and third solutions makes the most sense for this project. Actually, if the “clever logic” is actually a generative algorithm (generating obstacles that can always be avoided), it will be easy to script its parameters to control the pace of each level.
One other important point I thought about yesterday was playing is that we may make the rocks not so “deadly”: make them just slow you down, and have mines that are actually deadly. This makes sense, since it will allow us to have both types of gameplay, and provide some progression between the levels. My original idea was to have three levels in total, with different graphics and growing levels of difficulty. I’ve changed my mind: completing a level is a big reward for the player, so it’s better to have more progression stages and give them important rewards more often. Thus, my current idea is to make 9 levels, three levels each in each of the main three worlds with different graphics. I will also try to come up with some gameplay elements to add variety to the levels – although even just increasing the minimum/maximum cruise speed of the ship in each level will probably provide enough difficulty increase to make it noticeably different to play.
Just to share my outlook from where I am now, I am thinking we can probably add other types of obstacles beyond rocks and mines, possibly with some simple behavior, which would provide some variety. Browsing the Tyrian graphics sure provides some inspiring ideas quite easily: rotating bladed shurikens, robotic probes, daemon-like creatures, etc… having one or two new elements in each of the three “worlds” seems sufficient for a varied gameplay experience.
I would also love to have an end-of-world boss on each, but I’m unsure I can pull that off in the week. We’ll see!
One other note: yesterday night I took a little time and added three important gameplay elements: fuel blobs that you can pick up, shooting rockets with the spacebar, and accelerating/slowing down with UP/DOWN. I think it’s a grand total of 20 lines of code to implement that. It only goes to show how simple some things are… ah, and by the way, I also increased the manoeuvrability of the ship by increasing SHIP_MAX_TILT from 1.0 to 2.0. Together with the ability to “slow down”, it allowed me to complete the level today! I still have to think how the accelerate/slow-down option affects things. Going slower is clearly easier, so there has to be some reward to going fast. Maybe a time limit for a level, or extra score for completing it faster? We’ll see.
Plan for the day
So before getting started, here is my plan for today:
Part 1: Gameplay control
– Implement controlled obstacle generation to obtain controlled gameplay
– Implement rocks and mines causing low/high damage
– Get to a reasonable level progression with the above: controlled and growing difficulty, but always doable
Part 2: “Special effects”
– Sound
– Particle effects
– Fonts for text messages
I’m not sure I can do everything today, but let’s try it. Tomorrow I will have to finalize the level structure (the 9 levels with their graphics and gameplay parameters), and after that we will be off to finish production (menus, installer, etc…) and of course we will keep playtesting and tweaking gameplay things and effects until the very last minute.
Starting to control gameplay…
I’ve been playing quite a bit to try and understand the experience. I’ve realized that what controls the difficulty is how easy it is to find a gap in the upcoming rocks and fly to it. So, even if the algorithm has to generate rocks, it has to focus on the gaps. This also provides a great way to adjust the algorithm to generate challenges of different difficulty: more and wider gaps for easy difficulty, fewer and narrower gaps for more challenging situations.
Let me share a first stab at controlling the content generation. This is not ready, but in the name of showing intermediate steps, here you have a new version. It incorporates floating fuel clumps and you can shoot rockets with the spacebar (both are non-functional). You can also accelerate and slow down. You need new graphics too (download here: http://jonbho.net/wp-content/uploads/2013/08/sc-gfx-3.zip).
Here is the “somewhat-controlled” content-generation code from game.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
// highlights from game4.cpp ... #define LOG(ALL_ARGS) printf ALL_ARGS //#define LOG(ALL_ARGS) ... #define FIRST_CHALLENGE 3000.f ... //----------------------------------------------------------------------------- // Level generation, called from RunGame() every frame float g_next_challenge_area = FIRST_CHALLENGE; void GenNextElements() { // Called every game loop, but only does work when we are close to the next "challenge area" if (g_current_race_pos + 2 * G_HEIGHT > g_next_challenge_area) { float current_y = g_next_challenge_area; LOG(("Current: %f\n", g_next_challenge_area)); // Choose how many layers of rocks int nlayers = (int)CORE_URand(1, 3); LOG((" nlayers: %d\n", nlayers)); for (int i = 0; i < nlayers; i++) { LOG((" where: %f\n", current_y)); // Choose how many rocks int nrocks = (int)CORE_URand(1, 2); LOG((" nrocks: %d\n", nrocks)); // Gen rocks for (int i = 0; i < nrocks; i++) { InsertEntity(E_ROCK, vmake(CORE_FRand(0.f, G_WIDTH), current_y), vmake(CORE_FRand(-1.f, +1.f), CORE_FRand(-1.f, +1.f)), ROCK_RADIUS, g_rock[1/*CORE_URand(0,4)*/], true); } current_y += CORE_FRand(300.f, 600.f); } g_next_challenge_area = current_y + CORE_FRand(.5f * G_HEIGHT, 1.5f * G_HEIGHT); LOG(("Next: %f\n\n", g_next_challenge_area)); } } |
Things worth mentioning in the code:
- The content-generation smarts are in GenNextElements(), it’s called every time around the loop, but it only generates stuff when we are close enough to wherever we decided the next piece of content should be.
- Debug logging: I have added a #define for LOG that can ‘printf’ some information (helpful when debugging). The way I have done it, if I change the #define to the one commented out (without any body), it will just be as removing the logging statements.
- Also, I’ve made it always generate the same type of rock, until I adjust the collision boundaries, this will be the best way to have it working correctly.
You can see how now the content generation has more “structure”, the level is made up of a succession of challenges. Still, the challenges need work, since they are not always beatable yet, and they are not all that interesting. Anyway, going to post this and will come back later with something better.
(… a few hours later …)
Controlled gameplay generation
I think I’ve found what I was looking for. It was obvious in retrospect, as so many things often are. The trick is the following: since you always want to provide a path for the player to follow, you should just explicitly calculate it, and make sure that no obstacles obscure it! That way, you always allow the player to find a way, and you can also control difficulty with the maximum turn allowed in the path, the width around it you ensure remains clear, etc…
I have added the following functional game elements too: “juice” blobs that provide fuel, mines, drones (still passive), and I made rockets functional too. Now the level is very easy to overcome, but I think I now have all the elements necessary to control the difficulty and construct an interesting difficulty progression over the game levels.
No more gameplay work for today, but before I get working in special effects, here is the code in its current fashion for you to see (you need new resources with the drone & mine graphics: sc-gfx-4.zip):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
// highlights from game5.cpp ... #define SAFESUB(ARG_BASE, ARG_CHUNK) (ARG_BASE - ARG_CHUNK > 0 ? ARG_BASE - ARG_CHUNK : 0) #define SAFEADD(ARG_BASE, ARG_CHUNK, ARG_MAX) (ARG_BASE + ARG_CHUNK <= ARG_MAX ? ARG_BASE + ARG_CHUNK : ARG_MAX) #define MAX(ARG_A, ARG_B) ((ARG_A)>(ARG_B)?(ARG_A):(ARG_B)) #define MIN(ARG_A, ARG_B) ((ARG_A)<(ARG_B)?(ARG_A):(ARG_B)) ... #define ROCK_CRASH_ENERGY_LOSS 30.f #define MINE_CRASH_ENERGY_LOSS 80.f #define MAX_ENERGY 100.f #define MAX_FUEL 100.f #define ROCKET_SPEED 15.f #define MIN_TIME_BETWEEN_ROCKETS 1.f #define MIN_FUEL_FOR_HEAL MAX_FUEL/2.f #define FUEL_HEAL_PER_FRAME .2f #define ENERGY_HEAL_PER_FRAME .1f #define JUICE_FUEL 30.f ... #define SHIP_MAX_TILT 1.5f ... //----------------------------------------------------------------------------- // Level generation float g_next_challenge_area = FIRST_CHALLENGE; vec2 g_last_conditioned = vmake(0.f,0.f); #define PATH_TWIST_RATIO .5f // This means about 30 degrees maximum #define PATH_WIDTH (2.f * MAINSHIP_RADIUS) void GenNextElements() { // Called every game loop, but only does work when we are close to the next "challenge area" if (g_current_race_pos + G_HEIGHT > g_next_challenge_area) { float current_y = g_next_challenge_area; LOG(("Current: %f\n", g_next_challenge_area)); // Choose how many layers of rocks int nlayers = (int)CORE_URand(1, 20); LOG((" nlayers: %d\n", nlayers)); for (int i = 0; i < nlayers; i++) { LOG((" where: %f\n", current_y)); // Choose pass point float displace = (current_y - g_last_conditioned.y) * PATH_TWIST_RATIO; float bracket_left = g_last_conditioned.x - displace; float bracket_right = g_last_conditioned.x + displace; bracket_left = MAX(bracket_left, 2.f * MAINSHIP_RADIUS); bracket_right = MIN(bracket_right, G_WIDTH - 2.f * MAINSHIP_RADIUS); g_last_conditioned.y = current_y; g_last_conditioned.x = CORE_FRand(bracket_left, bracket_right); /*InsertEntity(E_JUICE, vmake(g_last_conditioned.x, g_last_conditioned.y), vmake(0.f,0.f), JUICE_RADIUS, g_juice, false, true);*/ // Choose how many rocks int nrocks = (int)CORE_URand(0, 3); LOG((" nrocks: %d\n", nrocks)); // Gen rocks for (int i = 0; i < nrocks; i++) { // Find a valid pos! vec2 rockpos; for (;;) { rockpos = vmake(CORE_FRand(0.f, G_WIDTH), current_y); if ( rockpos.x + ROCK_RADIUS < g_last_conditioned.x - PATH_WIDTH || rockpos.x - ROCK_RADIUS > g_last_conditioned.x + PATH_WIDTH) break; } // Insert obstacle EType t = E_ROCK; int gfx = g_rock[1/*CORE_URand(0,4)*/]; if (CORE_RandChance(0.1f)) { t = E_MINE; gfx = g_mine; } else if (CORE_RandChance(0.1f)) { t = E_DRONE; gfx = g_drone; } InsertEntity(t, rockpos, vmake(CORE_FRand(-.5f, +.5f), CORE_FRand(-.5f, +.5f)), //vmake(0.f,0.f), ROCK_RADIUS, gfx, true); } current_y += CORE_FRand(300.f, 600.f); } g_next_challenge_area = current_y + CORE_FRand(.5f * G_HEIGHT, 1.5f * G_HEIGHT); LOG(("Next: %f\n\n", g_next_challenge_area)); } } ... //----------------------------------------------------------------------------- void ResetNewGame() { // Reset everything for a new game... g_next_challenge_area = FIRST_CHALLENGE; g_last_conditioned = vmake(.5f * G_WIDTH, 0.f); g_current_race_pos = 0.f; g_camera_offset = 0.f; g_rock_chance = START_ROCK_CHANCE_PER_PIXEL; g_gs = GS_STARTING; g_gs_timer = 0.f; // Start logic for (int i = 0; i < MAX_ENTITIES; i++) g_entities[i].type = E_NULL; InsertEntity(E_MAIN, vmake(G_WIDTH/2.0, G_HEIGHT/8.f), vmake(0.f, SHIP_START_SPEED), MAINSHIP_RADIUS, g_ship_C, true); } ... //----------------------------------------------------------------------------- void RunGame() { // Control main ship if (g_gs == GS_VICTORY || g_gs == GS_STARTING) { if (MAIN_SHIP.vel.y < SHIP_CRUISE_SPEED) MAIN_SHIP.vel.y = SAFEADD(MAIN_SHIP.vel.y, SHIP_INC_SPEED, SHIP_CRUISE_SPEED); MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, FRAME_FUEL_COST); } // Heal main ship if (g_gs != GS_DYING) { if (MAIN_SHIP.energy < MAX_ENERGY && MAIN_SHIP.fuel >= MIN_FUEL_FOR_HEAL) { MAIN_SHIP.energy = SAFEADD(MAIN_SHIP.energy, ENERGY_HEAL_PER_FRAME, MAX_ENERGY); MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, FUEL_HEAL_PER_FRAME); LOG(("- energy: %f, fuel: %f\n", MAIN_SHIP.energy, MAIN_SHIP.fuel)); } } // Move entities for (int i = MAX_ENTITIES - 1; i >= 0; i--) { if (g_entities[i].type != E_NULL) { g_entities[i].pos = vadd(g_entities[i].pos, g_entities[i].vel); // Remove entities that fell off the screen if (g_entities[i].pos.y < g_camera_offset - G_HEIGHT) g_entities[i].type = E_NULL; } } // Advance 'stars' for (int i = 0; i < MAX_ENTITIES; i++) { if (g_entities[i].type == E_STAR) { g_entities[i].gfxscale *= 1.008f; } } // Dont let steering off the screen! if (MAIN_SHIP.pos.x < MAINSHIP_RADIUS) MAIN_SHIP.pos.x = MAINSHIP_RADIUS; if (MAIN_SHIP.pos.x > G_WIDTH - MAINSHIP_RADIUS) MAIN_SHIP.pos.x = G_WIDTH - MAINSHIP_RADIUS; // Check collisions if (g_gs == GS_PLAYING) { // Check everything agains ship for (int i = 1; i < MAX_ENTITIES; i++) { // Should check against ship? if ( g_entities[i].type == E_ROCK || g_entities[i].type == E_JUICE || g_entities[i].type == E_MINE || g_entities[i].type == E_DRONE ) { if (vlen2(vsub(g_entities[i].pos, MAIN_SHIP.pos)) < CORE_FSquare(g_entities[i].radius+MAIN_SHIP.radius)) { switch (g_entities[i].type) { case E_ROCK: if (g_entities[i].energy > 0) { MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, ROCK_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; g_entities[i].vel = vscale(vunit(vsub(g_entities[i].pos, MAIN_SHIP.pos)), CRASH_VEL); g_entities[i].energy = 0; } break; case E_JUICE: MAIN_SHIP.fuel = SAFEADD(MAIN_SHIP.fuel, JUICE_FUEL, MAX_FUEL); g_entities[i].type = E_NULL; break; case E_MINE: MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, MINE_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; g_entities[i].type = E_NULL; break; case E_DRONE: MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, MINE_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; g_entities[i].type = E_NULL; break; default: break; } } } else if (g_entities[i].type == E_ROCKET) { // Check all rocks against this rocket for (int j = 1; j < MAX_ENTITIES; j++) { // Should check against ship? if ( g_entities[j].type == E_ROCK || g_entities[j].type == E_MINE || g_entities[j].type == E_DRONE ) { if (vlen2(vsub(g_entities[i].pos, g_entities[j].pos)) < CORE_FSquare(g_entities[i].radius+g_entities[j].radius)) { g_entities[i].type = E_NULL; g_entities[j].type = E_NULL; // Rocket hit the target! /*switch (g_entities[j].type) { }*/ break; // Stop checking rocks! } } } } } } // Generate new level elements as we advance GenNextElements(); // Possibly insert new rock if (g_gs == GS_PLAYING) { float trench = MAIN_SHIP.pos.y - g_current_race_pos; // How much advanced from previous frame if (CORE_RandChance(trench * JUICE_CHANCE_PER_PIXEL)) InsertEntity(E_JUICE, vmake(CORE_FRand(0.f, G_WIDTH), g_camera_offset + G_HEIGHT + GEN_IN_ADVANCE), vmake(CORE_FRand(-1.f, +1.f), CORE_FRand(-1.f, +1.f)), JUICE_RADIUS, g_juice, false, true); } // Set camera to follow the main ship g_camera_offset = MAIN_SHIP.pos.y - G_HEIGHT/8.f; g_current_race_pos = MAIN_SHIP.pos.y; if (g_gs == GS_PLAYING) { if (g_current_race_pos >= RACE_END) { g_gs = GS_VICTORY; g_gs_timer = 0.f; MAIN_SHIP.gfxadditive = true; } } // Advance game mode g_gs_timer += FRAMETIME; switch (g_gs) { case GS_STARTING: if (g_gs_timer >= STARTING_TIME) { g_gs = GS_PLAYING; g_gs_timer = 0.f; } break; case GS_DYING: if (g_gs_timer >= DYING_TIME) { ResetNewGame(); } break; case GS_PLAYING: if (MAIN_SHIP.energy <= 0.f || MAIN_SHIP.fuel <= 0.f) { g_gs = GS_DYING; g_gs_timer = 0.f; MAIN_SHIP.gfx = g_ship_RR; } break; case GS_VICTORY: if (CORE_RandChance(1.f/10.f)) InsertEntity(E_STAR, MAIN_SHIP.pos, vadd(MAIN_SHIP.vel,vmake(CORE_FRand(-5.f, 5.f), CORE_FRand(-5.f,5.f))), 0, g_star, false, true); if (g_gs_timer >= VICTORY_TIME) ResetNewGame(); break; } g_time_from_last_rocket += FRAMETIME; } ... |
And here is how it looks now:
Spacecrash: Day 3 of 7 (mid-day) from Jon Beltran de Heredia on Vimeo.
As you see, quite a lot more functionality, with low quality looks. After this, I am off to work in in sound and graphics effects. Will post again later.
Some sound and particle effects
After investing some time, I have to say that I’ve blown the budget here. I expected to have nice sounds and particle effects by the end of today, and couldn’t do it. I have added a minimal sound engine based on OpenAL, and also some particle systems code. But I will need quite a bit more time to tweak these.
It’s still good to have these though, most of the core work for these areas is done now. Here are the remaining points:
- Good sound selection
- Particle effects properly calibrated, possibly working in screen space rather than world space
- Lots of particle systems have to be created & configured for explosions, etc…
We’ll get there in time. I don’t want to miss the whole schedule, so I’ll keep the global schedule and work on these remaining points on the side. Friday and Saturday’s work should allow plenty of time on the side (hopefully!).
To see the current version, first download the new data including sounds (sc-data-5.zip). And then you will need new code. I’ve added stuff to the core module, and corrected a couple of things, so here it is again:
First core.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// core.h #ifndef _CORE_H_ #define _CORE_H_ //----------------------------------------------------------------------------- inline float CORE_FRand(float from, float to) { return from + (to-from)*(rand()/(float)RAND_MAX); } inline unsigned CORE_URand(unsigned from, unsigned to) { return from + rand()%((unsigned)(to-from+1)); } inline bool CORE_RandChance(float chance) { return CORE_FRand(0.f, 1.f) < chance; } inline float CORE_FSquare(float f) { return f * f; } //----------------------------------------------------------------------------- struct rgba { float r, g, b, a; }; inline rgba makergba(float r, float g, float b, float a) { rgba c; c.r = r; c.g = g; c.b = b; c.a = a; return c; } #define RGBA(rr,gg,bb,aa) makergba(rr/255.f, gg/255.f, bb/255.f, aa/255.f) #define COLOR_WHITE makergba(1.f,1.f,1.f,1.f) //----------------------------------------------------------------------------- // Bitmap/texture functions int CORE_LoadBmp(const char filename[], bool wrap); ivec2 CORE_GetBmpSize(int texix); GLuint CORE_GetBmpOpenGLTex(int texix); void CORE_UnloadBmp(int texix); void CORE_RenderCenteredSprite(vec2 pos, vec2 size, int texix, rgba color = COLOR_WHITE, bool additive = false); //----------------------------------------------------------------------------- // Sound bool CORE_InitSound(); void CORE_EndSound(); uint CORE_LoadWav (const char filename[]); void CORE_UnloadWav (uint snd); void CORE_PlaySound (uint snd, float volume, float pitch); void CORE_PlayLoopSound (unsigned loopchannel, ALuint snd, float volume, float pitch); void CORE_SetLoopSoundParam (unsigned loopchannel, float volume, float pitch); #endif |
And here are the highlights from core.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
// highlights from core.cpp ... //----------------------------------------------------------------------------- GLuint CORE_GetBmpOpenGLTex(int texix) { return g_textures[texix].tex; } ... //============================================================================= // Sound (OpenAL, WAV files), leave last one for music! #define SND_MAX_SOURCES 8 #define SND_MAX_LOOP_SOUNDS 2 ALuint SND_Sources[SND_MAX_SOURCES]; int SND_NextSource = 0; //----------------------------------------------------------------------------- bool CORE_InitSound() { ALCcontext *context; ALCdevice *device; device = alcOpenDevice(NULL); if (device) { context = alcCreateContext(device,NULL); alcMakeContextCurrent(context); alGenSources(SND_MAX_SOURCES, SND_Sources); alGetError(); return true; } else return false; } //----------------------------------------------------------------------------- void CORE_EndSound() { ALCdevice *device; ALCcontext *context; context = alcGetCurrentContext(); device = alcGetContextsDevice(context); alDeleteSources(SND_MAX_SOURCES, SND_Sources); alcMakeContextCurrent(NULL); alcDestroyContext(context); alcCloseDevice(device); } //----------------------------------------------------------------------------- void CORE_PlaySound(ALuint snd, float volume, float pitch) { // Stop and play! alSourceStop(SND_Sources[SND_NextSource]); alSourcei(SND_Sources[SND_NextSource], AL_BUFFER, snd); alSourcef(SND_Sources[SND_NextSource], AL_GAIN, volume); alSourcef(SND_Sources[SND_NextSource], AL_PITCH, pitch); alSourcePlay(SND_Sources[SND_NextSource]); SND_NextSource++; if (SND_NextSource == SND_MAX_SOURCES-SND_MAX_LOOP_SOUNDS) SND_NextSource = 0; } //----------------------------------------------------------------------------- void CORE_PlayLoopSound (unsigned loopchannel, ALuint snd, float volume, float pitch) { if (loopchannel >= SND_MAX_LOOP_SOUNDS) return; alSourceStop(SND_Sources[SND_MAX_SOURCES-loopchannel]); alSourcei(SND_Sources[SND_MAX_SOURCES-loopchannel], AL_BUFFER, snd); alSourcef(SND_Sources[SND_MAX_SOURCES-loopchannel], AL_GAIN, volume); alSourcei(SND_Sources[SND_MAX_SOURCES-loopchannel], AL_LOOPING, AL_TRUE); alSourcePlay(SND_Sources[SND_MAX_SOURCES-loopchannel]); } //----------------------------------------------------------------------------- void CORE_SetLoopSoundParam (unsigned loopchannel, float volume, float pitch) { if (loopchannel >= SND_MAX_LOOP_SOUNDS) return; alSourcef(SND_Sources[SND_MAX_SOURCES-loopchannel], AL_GAIN, volume); alSourcef(SND_Sources[SND_MAX_SOURCES-loopchannel], AL_PITCH, pitch); } //----------------------------------------------------------------------------- void CORE_StopLoopSound(unsigned loopchannel) { alSourceStop(SND_Sources[SND_MAX_SOURCES-loopchannel]); } //----------------------------------------------------------------------------- struct CORE_RIFFHeader { byte chunkID[4]; // 'RIFF' byte chunkSize[4]; byte format[4]; // 'WAVE' }; struct CORE_RIFFChunkHeader { byte subChunkID[4]; byte subChunkSize[4]; }; struct CORE_WAVEFormatChunk { byte audioFormat[2]; byte numChannels[2]; byte sampleRate[4]; byte byteRate[4]; byte blockAlignp[2]; byte bitsPerSample[2]; }; //----------------------------------------------------------------------------- #define MAX_WAV_SIZE 32*1024*1024 // Max 32Mb sound! static byte soundloadbuffer[MAX_WAV_SIZE]; ALuint CORE_LoadWav(const char filename[]) { ALuint retval = UINT_MAX; CORE_RIFFHeader hdr; int fd = open(filename, O_RDONLY); if (fd != -1) { read(fd, &hdr, sizeof(hdr)); if ( hdr.chunkID[0] == 'R' && hdr.chunkID[1] == 'I' && hdr.chunkID[2] == 'F' && hdr.chunkID[3] == 'F' && hdr.format [0] == 'W' && hdr.format [1] == 'A' && hdr.format [2] == 'V' && hdr.format [3] == 'E' ) { CORE_WAVEFormatChunk fmt; memset(&fmt, 0, sizeof(fmt)); for (;;) { CORE_RIFFChunkHeader chunkhdr; if (read(fd, &chunkhdr, sizeof(chunkhdr)) < sizeof(chunkhdr)) break; dword chunkdatasize = READ_LE_DWORD(chunkhdr.subChunkSize); if (chunkhdr.subChunkID[0] == 'f' && chunkhdr.subChunkID[1] == 'm' && chunkhdr.subChunkID[2] == 't' && chunkhdr.subChunkID[3] == ' ') { read(fd, &fmt, sizeof(fmt)); lseek(fd, ((1 + chunkdatasize) & -2) - sizeof(fmt), SEEK_CUR); // Skip to next chunk } else if (chunkhdr.subChunkID[0] == 'd' && chunkhdr.subChunkID[1] == 'a' && chunkhdr.subChunkID[2] == 't' && chunkhdr.subChunkID[3] == 'a') { dword contentsize = chunkdatasize; if (contentsize > sizeof(soundloadbuffer)) contentsize = sizeof(soundloadbuffer); read(fd, soundloadbuffer, contentsize); bool valid = true; ALsizei al_size = contentsize; ALsizei al_frequency = READ_LE_DWORD(fmt.sampleRate); ALenum al_format = (ALenum)-1; if (READ_LE_WORD(fmt.numChannels) == 1) { if (READ_LE_WORD(fmt.bitsPerSample) == 8 ) al_format = AL_FORMAT_MONO8; else if (READ_LE_WORD(fmt.bitsPerSample) == 16) al_format = AL_FORMAT_MONO16; else valid = false; } else if (READ_LE_WORD(fmt.numChannels) == 2) { if (READ_LE_WORD(fmt.bitsPerSample) == 8 ) al_format = AL_FORMAT_STEREO8; else if (READ_LE_WORD(fmt.bitsPerSample) == 16) al_format = AL_FORMAT_STEREO16; else valid = false; } if (valid) { ALuint al_buffer = UINT_MAX; alGenBuffers(1, &al_buffer); alBufferData(al_buffer, al_format, soundloadbuffer, al_size, al_frequency); retval = al_buffer; } break; } else lseek(fd, ((1 + READ_LE_DWORD(chunkhdr.subChunkSize)) & -2), SEEK_CUR); // Skip to next chunk } } close(fd); } return retval; } //----------------------------------------------------------------------------- void CORE_UnloadWav(ALuint snd) { alDeleteBuffers(1, &snd); } |
As you can see, I corrected a few typos in core.h, added a new function to get the underlying OpenGL texture for a texture-manager index, and I added an OpenAL-based sound engine in less than 200 lines of code.
And finally, here are the highlights from the new game module, which includes sounds and particle effects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 |
// highlights from game6.cpp ... #define SHIP_INC_SPEED .1f // slower accel/slow-down ... //============================================================================= // Textures management enum TexId { T_FONT, T_PARTICLE, T_SHIP_LL, T_SHIP_L, T_SHIP_C, T_SHIP_R, T_SHIP_RR, T_BKG0, T_ROCK0, T_ROCK1, T_ROCK2, T_ROCK3, T_ROCK4, T_PEARL, T_ENERGY, T_FUEL, T_STAR, T_JUICE, T_ROCKET, T_MINE, T_DRONE0, T_DRONE1, T_DRONE2 }; struct Texture { char name[100]; bool wrap; GLuint tex; }; Texture textures[] = { { "data/Kromasky.bmp" , false, 0 }, { "data/Particle.bmp" , false, 0 }, { "data/ShipLL.bmp" , false, 0 }, { "data/ShipL.bmp" , false, 0 }, { "data/ShipC.bmp" , false, 0 }, { "data/ShipR.bmp" , false, 0 }, { "data/ShipRR.bmp" , false, 0 }, { "data/bkg0.bmp" , false, 0 }, { "data/Rock0.bmp" , false, 0 }, { "data/Rock1.bmp" , false, 0 }, { "data/Rock2.bmp" , false, 0 }, { "data/Rock3.bmp" , false, 0 }, { "data/Rock4.bmp" , false, 0 }, { "data/Pearl.bmp" , false, 0 }, { "data/Energy.bmp" , false, 0 }, { "data/Fuel.bmp" , false, 0 }, { "data/Star.bmp" , false, 0 }, { "data/Juice.bmp" , false, 0 }, { "data/Rocket.bmp" , false, 0 }, { "data/Mine.bmp" , false, 0 }, { "data/Drone0.bmp" , false, 0 }, { "data/Drone1.bmp" , false, 0 }, { "data/Drone2.bmp" , false, 0 } }; void LoadTextures() { for (int i = 0; i < SIZE_ARRAY(textures); i++) textures[i].tex = CORE_LoadBmp(textures[i].name, true); } void UnloadTextures() { for (int i = 0; i < SIZE_ARRAY(textures); i++) CORE_UnloadBmp(textures[i].tex); } GLuint Tex(TexId id) { return textures[id].tex; } //============================================================================= // Sound engine enum SoundId { SND_THUMP, SND_EXPLOSSION, SND_ENGINE, SND_SUCCESS }; struct Sound { char name[100]; int bufid; }; Sound sounds[] = { { "data/410__tictacshutup__thump-1.wav" , 0 }, { "data/94185__nbs-dark__explosion.wav" , 0 }, { "data/ffff.wav" , 0 }, { "data/171671__fins__success-1.wav" , 0 } }; void LoadSounds() { for (int i = 0; i < SIZE_ARRAY(sounds); i++) sounds[i].bufid = CORE_LoadWav(sounds[i].name); } void UnloadSounds() { for (int i = 0; i < SIZE_ARRAY(sounds); i++) CORE_UnloadWav(sounds[i].bufid); } void PlaySound(SoundId id, float vol = SND_DEFAULT_VOL, float freq = 1.f) { CORE_PlaySound(sounds[id].bufid, vol, freq); } void PlayLoopSound (unsigned loopchannel, SoundId id, float vol, float pitch) { CORE_PlayLoopSound(loopchannel, sounds[id].bufid, vol, pitch); } void SetLoopSoundParam (unsigned loopchannel, float vol, float pitch) { CORE_SetLoopSoundParam(loopchannel, vol, pitch); } //============================================================================= // Particle systems manager enum PSType { PST_NULL, PST_WATER, PST_FIRE, PST_SMOKE, PST_DUST, PST_GOLD }; struct PSDef { TexId texture; bool additive; int newpartsperframe; int death; vec2 force; float startpos_random; vec2 startspeed_fixed; float startspeed_random; float startradius_min, startradius_max; rgba startcolor_fixed; rgba startcolor_random; }; PSDef psdefs[] = { // GFX ADD N DTH FORCE rndPos SPEED rndSPD Rmin Rmax clr clr-rand /* null */ { }, /* water */ { T_PARTICLE, true , 4, 150, vmake(0.f, -0.025f), 4.f, vmake(0.f, 0.45f), .1f, 8.f, 10.f, RGBA( 64, 64, 255, 128), RGBA(0, 0, 0, 0) }, /* fire */ { T_PARTICLE, true , 8, 60, vmake(0.f, -0.045f), 4.f, vmake(0.f,+0.25f), .1f, 8.f, 16.f, RGBA(255, 192, 128, 128), RGBA(0, 0, 0, 0) }, /* smoke */ { T_PARTICLE, false, 2, 250, vmake(0.f, 0.05f) , 4.f, vmake(0.f, 0.f) , .4f, 5.f, 12.f, RGBA( 64, 64, 64, 192), RGBA(0, 0, 0, 0) }, /* dust */ { T_PARTICLE, false, 4, 100, vmake(0.f, 0.05f) , 4.f, vmake(0.f, 0.f) , .4f, 3.f, 6.f, RGBA(192, 192, 192, 192), RGBA(0, 0, 0, 0) }, /* gold */ { T_PARTICLE, true , 1, 50, vmake(0.f, 0.f ) , 4.f, vmake(0.f, 0.f) , .3f, 3.f, 6.f, RGBA(192, 192, 64, 192), RGBA(0, 0, 0, 0) }, }; //============================================================================= // Particle system model #define MAX_PSYSTEMS 64 #define MAX_PARTICLES 512 struct Particle { byte active; byte padding; word age; vec2 pos; vec2 vel; float radius; rgba color; }; struct PSystem { PSType type; vec2 source_pos; vec2 source_vel; Particle particles[MAX_PARTICLES]; }; PSystem psystems[MAX_PSYSTEMS]; //----------------------------------------------------------------------------- void ResetPSystems() { for (int i = 0; i < MAX_PSYSTEMS; i++) psystems[i].type = PST_NULL; } //----------------------------------------------------------------------------- int CreatePSystem(PSType type, vec2 pos, vec2 vel) { for (int i = 0; i < MAX_PSYSTEMS; i++) { if (psystems[i].type == PST_NULL) { psystems[i].type = type; psystems[i].source_pos = pos; psystems[i].source_vel = vel; for (int j = 0; j < MAX_PARTICLES; j++) psystems[i].particles[j].active = 0; return i; } } return -1; } //----------------------------------------------------------------------------- void KillPSystem(int ix) { if (ix >= 0 && ix < MAX_PSYSTEMS) psystems[ix].type = PST_NULL; } //----------------------------------------------------------------------------- void SetPSystemSource(int ix, vec2 pos, vec2 vel) { if (ix >= 0 && ix < MAX_PSYSTEMS) { psystems[ix].source_pos = pos; psystems[ix].source_vel = vel; } } //----------------------------------------------------------------------------- void RenderPSystems(vec2 offset) { glEnable(GL_BLEND); for (int i = 0; i < MAX_PSYSTEMS; i++) { if (psystems[i].type != PST_NULL) { if (psdefs[psystems[i].type].additive) glBlendFunc(GL_SRC_ALPHA, GL_ONE); else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture( GL_TEXTURE_2D, CORE_GetBmpOpenGLTex(Tex(psdefs[psystems[i].type].texture)) ); glBegin( GL_QUADS ); for (int j = 0; j < MAX_PARTICLES; j++) { if (psystems[i].particles[j].active) { vec2 pos = psystems[i].particles[j].pos; float radius = psystems[i].particles[j].radius; vec2 p0 = vsub( pos, vmake(radius, radius) ); vec2 p1 = vadd( pos, vmake(radius, radius) ); rgba color = psystems[i].particles[j].color; float r = color.r; float g = color.g; float b = color.b; float a = color.a; glColor4f( r, g, b, a); glTexCoord2d(0.0,0.0); glVertex2f(p0.x + offset.x, p0.y + offset.y); glTexCoord2d(1.0,0.0); glVertex2f(p1.x + offset.x, p0.y + offset.y); glTexCoord2d(1.0,1.0); glVertex2f(p1.x + offset.x, p1.y + offset.y); glTexCoord2d(0.0,1.0); glVertex2f(p0.x + offset.x, p1.y + offset.y); } } glEnd(); } } glColor4f(1.f, 1.f, 1.f, 1.); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //----------------------------------------------------------------------------- void RunPSystems() { for (int i = 0; i < MAX_PSYSTEMS; i++) { if (psystems[i].type != PST_NULL) { // New particles ----------------------------------------------------------------------- for (int j = 0; j < psdefs[psystems[i].type].newpartsperframe; j++) { for (int k = 0; k < MAX_PARTICLES; k++) { if (!psystems[i].particles[k].active) { psystems[i].particles[k].active = 1; psystems[i].particles[k].age = 0; psystems[i].particles[k].pos = vadd(psystems[i].source_pos, vmake( CORE_FRand(-psdefs[psystems[i].type].startpos_random, +psdefs[psystems[i].type].startpos_random) ,CORE_FRand(-psdefs[psystems[i].type].startpos_random, +psdefs[psystems[i].type].startpos_random) ) ); psystems[i].particles[k].vel = vadd(psystems[i].source_vel, vmake( psdefs[psystems[i].type].startspeed_fixed.x + CORE_FRand(-psdefs[psystems[i].type].startspeed_random, +psdefs[psystems[i].type].startspeed_random), psdefs[psystems[i].type].startspeed_fixed.y + CORE_FRand(-psdefs[psystems[i].type].startspeed_random, +psdefs[psystems[i].type].startspeed_random) ) ); psystems[i].particles[k].radius = CORE_FRand(psdefs[psystems[i].type].startradius_min, psdefs[psystems[i].type].startradius_max); psystems[i].particles[k].color = psdefs[psystems[i].type].startcolor_fixed; break; // Added! } } } // Run particles ----------------------------------------------------------------------- for (int k = 0; k < MAX_PARTICLES; k++) { if (psystems[i].particles[k].active) { psystems[i].particles[k].age++; if (psystems[i].particles[k].age > psdefs[psystems[i].type].death) psystems[i].particles[k].active = 0; else { // Move psystems[i].particles[k].pos = vadd(psystems[i].particles[k].pos, psystems[i].particles[k].vel); psystems[i].particles[k].vel = vadd(psystems[i].particles[k].vel, psdefs[psystems[i].type].force); // Color psystems[i].particles[k].color.a = (psdefs[psystems[i].type].death - psystems[i].particles[k].age)/255.f; } } } } } } //============================================================================= // Game //----------------------------------------------------------------------------- // Entities enum EType { E_NULL, E_MAIN, E_ROCK, E_STAR, E_JUICE, E_ROCKET, E_MINE, E_DRONE }; #define MAX_ENTITIES 64 struct Entity { EType type; vec2 pos; vec2 vel; float radius; float energy; float fuel; float tilt; float gfxscale; TexId gfx; bool gfxadditive; rgba color; bool has_shadow; int psystem; vec2 psystem_off; }; Entity g_entities[MAX_ENTITIES]; //----------------------------------------------------------------------------- int InsertEntity(EType type, vec2 pos, vec2 vel, float radius, TexId gfx, bool has_shadow, bool additive = false) { for (int i = 0; i < MAX_ENTITIES; i++) { if (g_entities[i].type == E_NULL) { g_entities[i].type = type; g_entities[i].pos = pos; g_entities[i].vel = vel; g_entities[i].radius = radius; g_entities[i].gfx = gfx; g_entities[i].energy = MAX_ENERGY; g_entities[i].fuel = MAX_FUEL; g_entities[i].tilt = 0.f; g_entities[i].gfxscale = 1.f; g_entities[i].gfxadditive = additive; g_entities[i].color = COLOR_WHITE; g_entities[i].has_shadow = has_shadow; g_entities[i].psystem = -1; g_entities[i].psystem_off = vmake(0.f,0.f); return i; } } return -1; } //----------------------------------------------------------------------------- void KillEntity(int ix) { if (ix >= 0 && ix <= MAX_ENTITIES) { g_entities[ix].type = E_NULL; if (g_entities[ix].psystem >= 0) KillPSystem(g_entities[ix].psystem); } } ... //----------------------------------------------------------------------------- // Level generation float g_next_challenge_area = FIRST_CHALLENGE; vec2 g_last_conditioned = vmake(0.f,0.f); #define PATH_TWIST_RATIO .5f // This means 30 degrees maximum #define PATH_WIDTH (2.f * MAINSHIP_RADIUS) void GenNextElements() { // Called every game loop, but only does work when we are close to the next "challenge area" if (g_current_race_pos + G_HEIGHT > g_next_challenge_area) { float current_y = g_next_challenge_area; LOG(("Current: %f\n", g_next_challenge_area)); // Choose how many layers of rocks int nlayers = (int)CORE_URand(1, 20); LOG((" nlayers: %d\n", nlayers)); for (int i = 0; i < nlayers; i++) { LOG((" where: %f\n", current_y)); // Choose pass point float displace = (current_y - g_last_conditioned.y) * PATH_TWIST_RATIO; float bracket_left = g_last_conditioned.x - displace; float bracket_right = g_last_conditioned.x + displace; bracket_left = MAX(bracket_left, 2.f * MAINSHIP_RADIUS); bracket_right = MIN(bracket_right, G_WIDTH - 2.f * MAINSHIP_RADIUS); g_last_conditioned.y = current_y; g_last_conditioned.x = CORE_FRand(bracket_left, bracket_right); /*InsertEntity(E_JUICE, vmake(g_last_conditioned.x, g_last_conditioned.y), vmake(0.f,0.f), JUICE_RADIUS, T_JUICE, false, true);*/ // Choose how many rocks int nrocks = (int)CORE_URand(0, 3); LOG((" nrocks: %d\n", nrocks)); // Gen rocks for (int i = 0; i < nrocks; i++) { // Find a valid pos! vec2 rockpos; for (int k = 0; k < 10; k++) // 10 attempts maximum, avoid infinite loops! { rockpos = vmake(CORE_FRand(0.f, G_WIDTH), current_y); if ( rockpos.x + ROCK_RADIUS < g_last_conditioned.x - PATH_WIDTH || rockpos.x - ROCK_RADIUS > g_last_conditioned.x + PATH_WIDTH) break; } // Insert obstacle EType t = E_ROCK; TexId gfx = T_ROCK1; if (CORE_RandChance(0.1f)) { t = E_MINE; gfx = T_MINE; } else if (CORE_RandChance(0.1f)) { t = E_DRONE; gfx = T_DRONE2; } InsertEntity(t, rockpos, vmake(CORE_FRand(-.5f, +.5f), CORE_FRand(-.5f, +.5f)), //vmake(0.f,0.f), ROCK_RADIUS, gfx, true); } current_y += CORE_FRand(300.f, 600.f); } g_next_challenge_area = current_y + CORE_FRand(.5f * G_HEIGHT, 1.5f * G_HEIGHT); LOG(("Next: %f\n\n", g_next_challenge_area)); } } //----------------------------------------------------------------------------- void Render() { glClear( GL_COLOR_BUFFER_BIT ); // Render background, only tiles within the camera view int first_tile = (int)floorf(g_camera_offset / G_HEIGHT); for (int i = first_tile; i < first_tile + 2; i++) { CORE_RenderCenteredSprite( vsub(vadd(vmake(G_WIDTH/2.0f,G_HEIGHT/2.0f), vmake(0.f, (float)i * G_HEIGHT)), vmake(0.f,g_camera_offset)), vmake(G_WIDTH,G_HEIGHT), Tex(T_BKG0)); } // Draw entities for (int i = MAX_ENTITIES - 1; i >= 0; i--) { if (g_entities[i].type != E_NULL) { ivec2 sz = CORE_GetBmpSize(Tex(g_entities[i].gfx)); vec2 pos = g_entities[i].pos; pos.x = (float)((int)pos.x); pos.y = (float)((int)pos.y); if (g_entities[i].has_shadow) CORE_RenderCenteredSprite( vadd(vsub(pos, vmake(0.f,g_camera_offset)), vmake(0.f, -SHADOW_OFFSET)), vmake(sz.x * SPRITE_SCALE * g_entities[i].gfxscale * SHADOW_SCALE, sz.y * SPRITE_SCALE * g_entities[i].gfxscale * SHADOW_SCALE), Tex(g_entities[i].gfx), makergba(0.f,0.f,0.f,0.4f), g_entities[i].gfxadditive ); CORE_RenderCenteredSprite( vsub(pos, vmake(0.f,g_camera_offset)), vmake(sz.x * SPRITE_SCALE * g_entities[i].gfxscale, sz.y * SPRITE_SCALE * g_entities[i].gfxscale), Tex(g_entities[i].gfx), g_entities[i].color, g_entities[i].gfxadditive ); } } RenderPSystems(vmake(0.f,-g_camera_offset)); if (g_gs != GS_VICTORY) { // Draw UI float energy_ratio = MAIN_SHIP.energy / MAX_ENERGY; CORE_RenderCenteredSprite( vmake(ENERGY_BAR_W/2.f, energy_ratio * ENERGY_BAR_H / 2.f), vmake(ENERGY_BAR_W, ENERGY_BAR_H * energy_ratio), Tex(T_ENERGY), COLOR_WHITE, true); float fuel_ratio = MAIN_SHIP.fuel / MAX_FUEL; CORE_RenderCenteredSprite( vmake(G_WIDTH - FUEL_BAR_W/2.f, fuel_ratio * FUEL_BAR_H / 2.f), vmake(FUEL_BAR_W, FUEL_BAR_H * fuel_ratio), Tex(T_FUEL), COLOR_WHITE, true); // Show your progression in the level int num_chunks = (int)((g_current_race_pos/RACE_END) * MAX_CHUNKS); for (int i = 0; i < num_chunks; i++) CORE_RenderCenteredSprite( vmake(G_WIDTH - 100.f, 50.f + i * 50.f), vmake(CHUNK_W, CHUNK_H), Tex(T_PEARL)); } } //----------------------------------------------------------------------------- void ResetNewGame() { // Reset everything for a new game... g_next_challenge_area = FIRST_CHALLENGE; g_last_conditioned = vmake(.5f * G_WIDTH, 0.f); g_current_race_pos = 0.f; g_camera_offset = 0.f; g_rock_chance = START_ROCK_CHANCE_PER_PIXEL; g_gs = GS_STARTING; g_gs_timer = 0.f; // Start logic for (int i = 0; i < MAX_ENTITIES; i++) g_entities[i].type = E_NULL; InsertEntity(E_MAIN, vmake(G_WIDTH/2.0, G_HEIGHT/8.f), vmake(0.f, SHIP_START_SPEED), MAINSHIP_RADIUS, T_SHIP_C, true); PlayLoopSound(1, SND_ENGINE, 0.7f, 0.3f); ResetPSystems(); MAIN_SHIP.psystem = CreatePSystem(PST_FIRE, MAIN_SHIP.pos, vmake(0.f,0.f)); MAIN_SHIP.psystem_off = vmake(0.f, -120.f); } //----------------------------------------------------------------------------- void RunGame() { // Control main ship if (g_gs == GS_VICTORY || g_gs == GS_STARTING) { if (MAIN_SHIP.vel.y < SHIP_CRUISE_SPEED) MAIN_SHIP.vel.y = SAFEADD(MAIN_SHIP.vel.y, SHIP_INC_SPEED, SHIP_CRUISE_SPEED); MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, FRAME_FUEL_COST); } SetLoopSoundParam(1, 0.7f, 0.4f + 0.2f * (MAIN_SHIP.vel.y - SHIP_START_SPEED)/(SHIP_CRUISE_SPEED - SHIP_START_SPEED)); // Heal main ship if (g_gs != GS_DYING) { if (MAIN_SHIP.energy < MAX_ENERGY && MAIN_SHIP.fuel >= MIN_FUEL_FOR_HEAL) { MAIN_SHIP.energy = SAFEADD(MAIN_SHIP.energy, ENERGY_HEAL_PER_FRAME, MAX_ENERGY); MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, FUEL_HEAL_PER_FRAME); } } // Move entities for (int i = MAX_ENTITIES - 1; i >= 0; i--) { if (g_entities[i].type != E_NULL) { g_entities[i].pos = vadd(g_entities[i].pos, g_entities[i].vel); // Remove entities that fell off the screen if (g_entities[i].pos.y < g_camera_offset - G_HEIGHT) KillEntity(i); if (g_entities[i].psystem != -1) SetPSystemSource(g_entities[i].psystem, vadd(g_entities[i].pos, g_entities[i].psystem_off), g_entities[i].vel); } } // Advance 'stars' for (int i = 0; i < MAX_ENTITIES; i++) { if (g_entities[i].type == E_STAR) { g_entities[i].gfxscale *= 1.008f; } } // Advance particle systems RunPSystems(); // Dont let steering off the screen! if (MAIN_SHIP.pos.x < MAINSHIP_RADIUS) MAIN_SHIP.pos.x = MAINSHIP_RADIUS; if (MAIN_SHIP.pos.x > G_WIDTH - MAINSHIP_RADIUS) MAIN_SHIP.pos.x = G_WIDTH - MAINSHIP_RADIUS; // Check collisions if (g_gs == GS_PLAYING) { // Check everything agains ship for (int i = 1; i < MAX_ENTITIES; i++) { // Should check against ship? if ( g_entities[i].type == E_ROCK || g_entities[i].type == E_JUICE || g_entities[i].type == E_MINE || g_entities[i].type == E_DRONE ) { if (vlen2(vsub(g_entities[i].pos, MAIN_SHIP.pos)) < CORE_FSquare(g_entities[i].radius+MAIN_SHIP.radius)) { switch (g_entities[i].type) { case E_ROCK: if (g_entities[i].energy > 0) { PlaySound(SND_THUMP); MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, ROCK_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; g_entities[i].vel = vscale(vunit(vsub(g_entities[i].pos, MAIN_SHIP.pos)), CRASH_VEL); g_entities[i].energy = 0; } break; case E_JUICE: MAIN_SHIP.fuel = SAFEADD(MAIN_SHIP.fuel, JUICE_FUEL, MAX_FUEL); KillEntity(i); break; case E_MINE: PlaySound(SND_EXPLOSSION); MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, MINE_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; KillEntity(i); break; case E_DRONE: MAIN_SHIP.energy = SAFESUB(MAIN_SHIP.energy, MINE_CRASH_ENERGY_LOSS); MAIN_SHIP.vel.y = SHIP_START_SPEED; KillEntity(i); break; default: break; } } } else if (g_entities[i].type == E_ROCKET) { // Check all rocks against this rocket for (int j = 1; j < MAX_ENTITIES; j++) { // Should check against ship? if ( g_entities[j].type == E_ROCK || g_entities[j].type == E_MINE || g_entities[j].type == E_DRONE ) { if (vlen2(vsub(g_entities[i].pos, g_entities[j].pos)) < CORE_FSquare(g_entities[i].radius+g_entities[j].radius)) { // Rocket hit the target! switch (g_entities[j].type) { case E_MINE: PlaySound(SND_EXPLOSSION); break; default: break; } KillEntity(i); KillEntity(j); break; // Stop checking rocks! } } } } } } // Generate new level elements as we advance GenNextElements(); // Possibly insert new rock if (g_gs == GS_PLAYING) { float trench = MAIN_SHIP.pos.y - g_current_race_pos; // How much advanced from previous frame if (CORE_RandChance(trench * JUICE_CHANCE_PER_PIXEL)) InsertEntity(E_JUICE, vmake(CORE_FRand(0.f, G_WIDTH), g_camera_offset + G_HEIGHT + GEN_IN_ADVANCE), vmake(CORE_FRand(-1.f, +1.f), CORE_FRand(-1.f, +1.f)), JUICE_RADIUS, T_JUICE, false, true); } // Set camera to follow the main ship g_camera_offset = MAIN_SHIP.pos.y - G_HEIGHT/8.f; g_current_race_pos = MAIN_SHIP.pos.y; if (g_gs == GS_PLAYING) { if (g_current_race_pos >= RACE_END) { g_gs = GS_VICTORY; g_gs_timer = 0.f; MAIN_SHIP.gfxadditive = true; PlaySound(SND_SUCCESS); } } // Advance game mode g_gs_timer += FRAMETIME; switch (g_gs) { case GS_STARTING: if (g_gs_timer >= STARTING_TIME) { g_gs = GS_PLAYING; g_gs_timer = 0.f; } break; case GS_DYING: if (g_gs_timer >= DYING_TIME) { ResetNewGame(); } break; case GS_PLAYING: if (MAIN_SHIP.energy <= 0.f || MAIN_SHIP.fuel <= 0.f) { g_gs = GS_DYING; g_gs_timer = 0.f; MAIN_SHIP.gfx = T_SHIP_RR; } break; case GS_VICTORY: if (CORE_RandChance(1.f/10.f)) InsertEntity(E_STAR, MAIN_SHIP.pos, vadd(MAIN_SHIP.vel,vmake(CORE_FRand(-5.f, 5.f), CORE_FRand(-5.f,5.f))), 0, T_STAR, false, true); if (g_gs_timer >= VICTORY_TIME) ResetNewGame(); break; } g_time_from_last_rocket += FRAMETIME; } //----------------------------------------------------------------------------- void ProcessInput() { if (g_gs == GS_PLAYING) { if (SYS_KeyPressed(' ') && g_time_from_last_rocket > MIN_TIME_BETWEEN_ROCKETS) { int e = InsertEntity(E_ROCKET, MAIN_SHIP.pos, vadd(MAIN_SHIP.vel, vmake(0.f, ROCKET_SPEED)), ROCKET_RADIUS, T_ROCKET, true); g_time_from_last_rocket = 0; g_entities[e].psystem = CreatePSystem(PST_FIRE, MAIN_SHIP.pos, vmake(0.f,0.f)); g_entities[e].psystem_off = vmake(0.f, -120.f); } bool up = SYS_KeyPressed(SYS_KEY_UP); bool down = SYS_KeyPressed(SYS_KEY_DOWN); bool left = SYS_KeyPressed(SYS_KEY_LEFT); bool right = SYS_KeyPressed(SYS_KEY_RIGHT); // Left-right movement if (left && !right) { MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, TILT_FUEL_COST); MAIN_SHIP.tilt -= SHIP_TILT_INC; } if (right && !left) { MAIN_SHIP.fuel = SAFESUB(MAIN_SHIP.fuel, TILT_FUEL_COST); MAIN_SHIP.tilt += SHIP_TILT_INC; } if (!left && !right) MAIN_SHIP.tilt *= (1.f - SHIP_TILT_FRICTION); if (MAIN_SHIP.tilt <= -SHIP_MAX_TILT) MAIN_SHIP.tilt = -SHIP_MAX_TILT; if (MAIN_SHIP.tilt >= SHIP_MAX_TILT) MAIN_SHIP.tilt = SHIP_MAX_TILT; MAIN_SHIP.vel.x += MAIN_SHIP.tilt; MAIN_SHIP.vel.x *= (1.f - SHIP_HVEL_FRICTION); // Accelerate/slowdown if (up && !down) MAIN_SHIP.vel.y += SHIP_INC_SPEED; if (down && !up) MAIN_SHIP.vel.y -= SHIP_INC_SPEED; if (MAIN_SHIP.vel.y > SHIP_MAX_SPEED) MAIN_SHIP.vel.y = SHIP_MAX_SPEED; if (MAIN_SHIP.vel.y < SHIP_MIN_SPEED) MAIN_SHIP.vel.y = SHIP_MIN_SPEED; float tilt = MAIN_SHIP.tilt; if (tilt < -.6f * SHIP_MAX_TILT) MAIN_SHIP.gfx = T_SHIP_LL; else if (tilt < -.2f * SHIP_MAX_TILT) MAIN_SHIP.gfx = T_SHIP_L; else if (tilt < +.2f * SHIP_MAX_TILT) MAIN_SHIP.gfx = T_SHIP_C; else if (tilt < +.6f * SHIP_MAX_TILT) MAIN_SHIP.gfx = T_SHIP_R; else MAIN_SHIP.gfx = T_SHIP_RR; } } //----------------------------------------------------------------------------- // Game state (apart from entities & other stand-alone modules) float g_time = 0.f; //----------------------------------------------------------------------------- // Main int Main(void) { // Start things up & load resources --------------------------------------------------- CORE_InitSound(); LoadTextures(); LoadSounds(); ResetNewGame(); // Set up rendering --------------------------------------------------------------------- glViewport(0, 0, SYS_WIDTH, SYS_HEIGHT); glClearColor( 0.0f, 0.1f, 0.3f, 0.0f ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( 0.0, G_WIDTH, 0.0, G_HEIGHT, 0.0, 1.0); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); // Main game loop! ====================================================================== while (!SYS_GottaQuit()) { Render(); SYS_Show(); ProcessInput(); RunGame(); SYS_Pump(); SYS_Sleep(16); g_time += FRAMETIME; } UnloadSounds(); UnloadTextures(); CORE_EndSound(); return 0; } |
To summarize the changes above:
- I added a better system to handle texture loading (based on enums and an array describing what textures to load), and converted all game code to use those enums (TexId).
- I added a small sound manager too to load sound files, and added relevant calls in the game logic to trigger sounds (and adjust the pitch of the engine sound for the main ship)
- I included code to simulate simple particle-systems, made the Render() function call the RenderPSystems() function, and allowed entities to have an associated particle system
- I am fully listing RunGame() and ProcessInput() above since, even if they are mostly unchanged, you can see where the changes related to texture handling, sounds and particle-systems fit.
The code above is crying for a few more refactorings: some unified entity-type management, so that you can call a single function and have it create the related sound and particle effects, etc… but it’s ok for now, we’ll add that soon.
Here is the complete source code as of the end of day 3: spacecrash-source-day3.zip
And here is how it looks and sounds now (pardon the poor sound quality, need to set up a better way to capture sound than using the built-in speakers & mike (!)):
Spacecrash: Day 3 of 7 from Jon Beltran de Heredia on Vimeo.
Tomorrow: levels! levels! levels!
And if you want to be notified when new articles to help you become a games developer are ready, just fill in the form below:
Hey,
You thought about putting a timer in order to give some kind of reward when the player goes faster… How about making the fuel decrease fast enough so that the player cannot reach the next fuel barrel if staying at lowest speed? That way, the player can “stock” fuel so he can decrease speed for more complicated areas at the end of the level.
Cheers,
Yes, I was thinking about something like that when I added fuel as an element… what you propose makes sense. I will keep thinking about it and testing things for a few more days until I find something that provides an interesting system.
What do you think of this : instead of being able to speed up and slow down yourself, she ship automatically speeds up (up to a limit), and the only way to slow down is to shoot a rocket, because of the recoil effect. And then, if you limit the amount of rockets, it becomes a matter of tactics when to use them. And then rockets could be another pickup as well.
As an added bonus : this brings back the controls from LEFT/RIGHT/SPEED_UP/SPEED_DOWN/FIRE to LEFT/RIGHT/FIRE, and this makes it easier to translate to a mobile platform.
That’s definitely a cool idea, will keep it in mind. My current idea for mobile is that accelerate/slow-down will be controlled by tilting the phone forward/backward. Temple Run gets away with having you tilt sideways, so it may work well. Gotta test it.
But I really like the idea of combining shoot & slow-down. Will have to try it. And if you do try it yourself, let me know!
Word of warning about the gyro controls… besides the need to calibrate, one must be careful with the rotation axes. Tilting sideways Temple Run-style usually works because the screen stays perpendicular to your eyes, whereas pitching forwards/backwards will affect the visibility of the screen and the perception of distance along the vertical axis.
Thanks! I was thinking about doing it “callibrated relative” to allow for different resting-state tilts. But indeed it will be tricky, though I definitely want to test how it feels. Maybe Francis’ idea above about needing to shoot to slow down is what can work best!
Well, I did manage to make the changes that I talked about.
I made the start speed lower and the max speed higher. When you shoot, your speed goes down a bit. I’ve also increased the fire rate. And of course you’re constantly speeding up. There are now rocket pickups and a graphic indicator on the left that shows how many rockets are left.
I added some extra graphics (just the rocket once rotated and once cropped) but I managed to make the bmp’s not work, even though I wrote them with paintbrush. Anyway, here’s my variation : https://www.dropbox.com/sh/4rktp3w29rnha70/ND1sKoyacW
I was thinking more along these lines:
Flying slow uses more fuel to cover the same distance than flying fast would. You start with not enough fuel to make it to the end (at least not when flying slow), so a player flying slow would have to pick up more fuel to be able to finish the level.
On a completely different note: I think the mine and the rockets, especially the rockets, are to large (in relation to the players ship). And the content generating code should take into account that the player should be able to pick up the fuel blobs, so they can’t be too close to the rocks (in the first video it happens several times the fuel blobs are actually on top of the rocks).
But I have to say I’m impressed with how far you’ve already taken this game in just a few days! I love reading this blog. Keep up the good work!
Yeah, some strategy is needed to make fuel/speed thing work. I am not convinced about the current “fuel is automatically spent to repair the ship” thing.
You are right about the sizes, I just threw them in. I will adjust those today and tomorrow. I like a large rocket though, it’s kind of cartoony (and with the proper sound & particle effects it should be really cool). Mines are really large though.
Fuel is just generated “randomly” now, and there is too much of it. Since I’ll be focusing on level generation today, hopefully I’ll be able to do something about it.
Thanks for your kind words.
Hey Jon, keep up the good work!
After the week is over, I’d love it if you could go into more detail about the core methods, both the GL and AL stuff. That’s the only part I don’t fully “get.”
Thanks again, you rock.
[…] Spacecrash day 3 of 7: gameplay revamped […]