166 Commits

Author SHA1 Message Date
eecfbf5d7c Dev version bump to 0.6.0-dev3
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 1m2s
I'm moving on from asset stuff, so I'm considering this a "new version."

Next up: Fixing the Makefile to understand the sound files.
2025-12-19 10:41:08 -06:00
1e09e3ce3a Fix: Include the sound asset for the thruster!
I forgot to check-in the file the other day. Big brain here in this
head.
2025-12-19 10:40:28 -06:00
19ac032792 Add proper meshes & materials for game objects
The asteroid circles have been replaced with polylines. I was going to
do a regular triangle mesh, but I don't want to figure out GLTF
loading or manually chunking the points into convex hulls.

Asteroid materials are now all populated and their GameAsset getters are
indexed correctly. I'm not sold on the size based color selection.
Later, I think I'll either remove the extra colors or let each of them
randomly apply to any asteroid.

The bullet is now a short line segment. Apparently I already wired in
the rotation logic, so pointing it correctly out of the ship already
works.
2025-12-19 10:29:48 -06:00
de75e25ca6 Add ship thruster sound
The player's Ship now has an AudioPlayer component constantly looping a
thruster sound effect. It starts paused and is only resumed when the
player fires the thruster.

As noted in the TODO comment at the top of the input_ship_thruster(...)
system, I need to figure out if I want to start using the `Single<>`
query parameter instead of a `Query<>` and then doing my own
null-ability checks (like what it does now).
2025-12-17 17:18:18 -06:00
d7802bdbed Add asteroid destruction sound 2025-12-17 16:18:31 -06:00
ae093d2c9c Add bullet/laser sound
Firing the weapon now makes a sound. I've implemented this by spawning
the playback component on the bullet rather than the gun. This seemed
easier than figuring out how to reset a playback component that lives on
the ship entity -- although thats probably better for memory access
patterns.
2025-12-17 14:29:57 -06:00
3963b548b9 Fix: Make shipwreck sound entity despawn itself
I started to work on weapon fire sounds and realized I don't know if the
entity and/or component get removed after playback ends. It turns out
that they DO NOT!... unless told to do so, like this.
2025-12-17 14:23:57 -06:00
b1fd2e5f73 Add a readme
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 1m54s
There hasn't been a README this whole time... I guess there hasn't been
anything I need to immediately communicate to someone looking at the
source repository.

There is now a README so I have somewhere to record the extra licensing
information (for the Kenney asset).
2025-12-17 11:01:23 -06:00
09ff4dc6ca First sound! Added ship explosion sound effect
It's a simple one-shot sound clip that gets dispatched as one more part
of the ship impact routine.

The GameAssets struct has been updated to have an array of handles for
audio assets (just the one, for now).

This sound file, and the next several, are all from Kenney
(www.kenney.nl).
2025-12-17 10:46:51 -06:00
a48dfc1d65 Finish the engine upgrade
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 2m1s
Events have been replaced with Messages, import paths have been updated
for new engine module layout, and minor API changes have been matched.
2025-12-17 10:15:33 -06:00
6e425e8eb9 WIP on engine upgrade 2025-12-17 09:44:48 -06:00
7bd88c702f Replace event derives with message derives 2025-12-17 09:44:48 -06:00
cfe35c61ed Rename crate::events to crate::messages
Bevy 0.17 introduces this idea of "Messages" which mostly replace the
previous usage of "Events." The old events still exist, but are meant
more for targetted actions -- something happening and immediately
triggering a function call on an observer.
2025-12-17 09:44:48 -06:00
13643f73fb Upgrade to Bevy 0.17... minus fixes for API change
Bevy 0.17 is out and I'm going to get started on an upgrade. Upgrading
dependencies will be it's own commit, as will many of the fixes. This
way I can cherry-pick anything, if need be.
2025-12-17 09:41:44 -06:00
8fc9e682cc Release v0.5.0
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 28s
2025-11-15 15:18:54 -06:00
be83be1a7b Compress the WASM file for even more space savings 2025-11-15 15:16:37 -06:00
3639122e54 Fix: install "asteroids.html" not "boids.html"
Yay for copying code around!
2025-11-15 15:16:02 -06:00
97e0313c23 Impl a basic scoring system
Games have scores, so I need a score counter... I guess.
2025-11-09 11:14:27 -06:00
de79ca0258 Apply clippy lint fix 2025-11-09 10:57:36 -06:00
1edbd3e78c Name oldest viable dependency versions
Semver compatible resolution means I still get the newest, so I want to
name the oldest that still works to let Cargo do it's thing.
2025-11-08 22:17:05 -06:00
5af59863a1 Release v0.4.0, now includes lockfile
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m23s
The only real change was the addition of some CSS. I'm recording the
lockfile so that consumers can more reliably build the same binary each
time.
2025-11-08 12:31:29 -06:00
84d93d496a Remove Linux-specific deps from web build
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m24s
The Alsa and Udev system dependencies are only required on Linux. The
WASM/WASI build doesn't use them, so they don't need to exist in the
build container.
2025-11-08 12:10:42 -06:00
4a9d252691 Update Dockerfile, copy everything, use makefile
I have figured out the `.dockerignore` file so I don't have to do manual
context size management like before.

The Dockerfile now uses the Makefile to ensure image builds contain the
same thing non-image builds would.
2025-11-08 12:08:45 -06:00
3c9a9a7d9d Add some CSS 2025-11-08 12:07:30 -06:00
010cbd6d4b Add an install target 2025-11-06 14:18:13 -06:00
918992702f Add standalone & bundle-able build variants
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 8m8s
Now there are build targets for producing a version that can be served
as-is, and another that can be included as a page in a larger site.
2025-11-06 10:48:06 -06:00
c8c64e4d22 Place Makefile 'configurables' up top
Variables that a package consumer might want to adjust should be placed
at the top of the file so they are immediately visible. Any constants
shall live below those (just the SRC folder, really).
2025-11-06 10:26:35 -06:00
88a1b0e44b Release: v0.3.0, drop "+patches" note on webpate
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m44s
2025-10-30 13:55:48 -05:00
aaab0757de Add a license to the project (AGPLv3)
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m6s
2025-10-30 12:47:22 -05:00
5aa47687a5 Add a Dockerfile for container-ized web hosting 2025-10-30 12:36:10 -05:00
01cef2dd97 Add a Makefile to automate the web build proc
This is also copied from my Boids project, just like the HTML page was.
2025-10-30 12:07:12 -05:00
fb5209a5c2 Have Bevy find assigned canvas element
Bevy creates it's own canvas element by default, but the custom page
defines its own. This makes Bevy go find that one.

The window sizing still works -- it simply resizes the canvas upon
starting. I'm not sure if I'll change that or remove the size from the
HTML. That's a tomorrow problem.
2025-10-30 12:00:09 -05:00
fe4e946e83 Add a custom webpage for the WASM build
It's just a copy of the page I made for my Boids program, but with all
the relevant names swapped to "asteroids".
2025-10-30 11:56:24 -05:00
7c385b1557 Make dynamic linking feature a default
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m17s
Now I don't need to keep setting the option on the command line. I'll
take it out (or use `--no-default-features`) when making the release
build.
2025-08-29 13:35:50 -05:00
746de2bd80 Add "Game Over" text to the game over screen
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m18s
2025-08-15 15:26:11 -05:00
73ee5e554b Reorder ship-collision steps, rm frozen debris
When the player gets a game-over, the debris is spawned and then frozen
in place as the physics system gets turned off. I can make sure it never
appears by writing the state change and returning early from the
function.

This means the asteroid despawning needs to happen before that point,
otherwise the asteroids would be left on screen.
2025-08-15 15:02:28 -05:00
0967795d51 Remove unnecessary mut on system parameter
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m4s
2025-08-14 22:33:53 -05:00
20c71658c3 Implement a basic ship debris effect
I'm stealing the thruster mesh, which itself is actually the ship's
mesh, to draw the debris particles. I'll come back and make the scatter
a bit better at some point, but for now it's passable.
2025-08-14 22:33:42 -05:00
960861af79 Add a sparkler component to flash entities
I'll be using this to make a sparkling effect on the debris field left
behind from a destroyed ship.

It can also be used to do the temporary invincibility effect when
(re)spawning the player.
2025-08-14 21:57:47 -05:00
4b70be7048 Fix and improve ButtonMenuAction doc comment 2025-08-14 20:54:29 -05:00
8bf21e74f0 Remove Rapier debug plugin 2025-08-14 18:25:33 -05:00
c0cf6d7f30 Fix: reset "get-ready" timer upon showing widget
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m21s
Closes #25: Reset "get ready" timer upon entering the get-ready state.
2025-08-14 18:20:50 -05:00
cc23e9e08e Despawn the player when exiting the Playing state
Closes #21: Despawn player ship when exiting `GameState::Playing`

I've also moved the `fn despawn<T>` utility to the lib.rs module.
2025-08-14 14:50:12 -05:00
cf9825fcc3 Fix: Starting game from GUI runs "get ready" timer
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m14s
Closes #23: Main menu's start button doesn't run the get-ready timer

I made the start button go directly to `GameState::Playing`, which is
not actually the right state for beginning a new game. Swap the states
and everything works again.
2025-08-14 14:39:24 -05:00
708f514582 Implement a proper gun fire-rate mechanism
There is now a `Weapon` component which is just a timer for the gun's
fire rate. It is ticked every frame, clamping at the "ready" state (0
time remaining).

The ship spawns with this thing, and the `input_ship_shoot` system has
been updated to use it.
2025-08-14 14:34:22 -05:00
0a7ffcfa0a Add reflection & debug inspector stuff to Score 2025-08-14 13:14:32 -05:00
40ee042b53 Implement the HUD for real
Now it works!... but it runs every single frame, probably causing a
bunch of unnecessary text rendering and UI layout operations. I'll have
to come back and make it event-based at some point.
2025-08-14 13:07:25 -05:00
9d9b25d1df Name the profiles to not suggest they're WASM-only
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m13s
2025-08-14 11:04:20 -05:00
89ee328807 A couple extra build profiles 2025-08-14 11:04:20 -05:00
90d8142855 Use wasm-server-runner as the WASM runner
This way I can `cargo run --target ...` and Cargo will spawn a dummy
webserver instead of attempting to execute the WASM file on my x86/arm
CPU.
2025-08-14 11:03:37 -05:00
10366b642c Add wasm-specific feature for RNG child dependency
The `rand` crate eventually depends on `getrandom` which requires a
different feature set when running in the browser. WASM has no OS, and
so no RNG provider... but the browser, specifically, has one that the
JavaScript runtime can touch. Enabling the "wasm_js" feature on
`getrandom` allowes it to use this backend.

An extra config option must *also* be passed to `rustc`. THis can be set
through the environment, or the config.toml. I've chosen the latter so I
don't need to think about it very often.
2025-08-14 11:03:37 -05:00
94e0cd0999 Add my own crate features to pass through to deps
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m25s
Closes #20

Now this crate can be told to build with or without certain behavior,
rather than needing to patch the Cargo.toml file.
2025-08-14 10:34:03 -05:00
18d026637b Bump the crate version
I marked 0.2 at some point, so I guess I should keep incrementing this
during development. The menus are finished, which is as good a
checkpoint as any.
2025-08-14 08:58:02 -05:00
51e6989ef4 Swap button colors to be less upsetting
Making everything gray is still boring as dirt, but at least it doesn't
look like debug info.
2025-08-14 08:55:13 -05:00
2ffc0e8861 Finish main-menu button handling
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m8s
2025-08-13 17:25:26 -05:00
d15b96ef48 Add "start" and "quit" buttons to title screen
I'm stealing the game-over plugin's button handling for use in the main
menu. I guess it turns out that my widgets are more generic than
intended.
2025-08-13 17:00:29 -05:00
0aefc96f7a Center the text, add a drop shadow 2025-08-13 16:03:40 -05:00
4102446e90 Rename main menu marker to "MarkerMainMenu" 2025-08-13 15:38:53 -05:00
f4df2ae33a Rearrange the main menu components & systems
I'm trying to keep things somewhat in order. Plugins, then components,
then systems. Within those, they're roughly ordered by game state.
2025-08-13 15:36:14 -05:00
fc43be0777 Hook up the action selectors to the buttons
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m8s
2025-08-13 14:22:00 -05:00
a74b99deb4 Visual button interaction is working, needs act
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m22s
2025-08-13 12:59:38 -05:00
2f9401e93f Begin GameOver scene, widget spawner works
I've taken a lot directly from the Bevy UI button example.
(https://bevy.org/examples/ui-user-interface/button/)

I'll make it look better later. For now, it just needs to exist. Onward
to the UI operation system!
2025-08-13 11:58:11 -05:00
54ef257ab4 Make generic UI despawning function 2025-08-13 11:56:35 -05:00
69bef24913 Collect GUI plugins at the top of the module
I want the different "scenes" to be their own plugins for ease of setup
and reading.

The main menu plugin has been renamed to have "Plugin" first. This is so
the lexical sort in the docs places all the plugins next to each other.

The "get-ready" plugin has been given an empty struct and an
`impl Plugin` to match the main menu plugin. I've started the game over
scene, but left it unimplemented.
2025-08-13 11:09:48 -05:00
df4479bf49 Remove collision debug print system 2025-08-13 10:33:59 -05:00
33828d6a85 Rewrite WorldSize as a newtype around Vec2
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m7s
Closes #16

Bevy provides Deref and DerefMut derives, so that's nice. I'm not sure
it makes any sense to keep the field private since those derefs expose
the Vec2 anyway. I added an `impl Default` anyway, though.
2025-08-12 23:39:19 -05:00
5e2018d3e4 Docs for physics module 2025-08-12 23:26:37 -05:00
7c877264a2 autoformat 2025-08-12 23:18:46 -05:00
16842c13f7 Docs for objects.rs 2025-08-12 23:18:33 -05:00
e199db16eb Docs for machinery.rs 2025-08-12 23:01:32 -05:00
f17910daef Docs for lib.rs 2025-08-12 22:41:37 -05:00
70f2313766 Improve documentation for the events
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
2025-08-12 11:33:00 -05:00
58bbc1e614 Fix documentation links 2025-08-11 23:50:43 -05:00
79679759c5 Move HUD spawning system into widgets
It actually needs to be completely replaced. When that finally happens,
the new bits will live here.
2025-08-11 23:42:06 -05:00
0e517de419 Move the title screen stuff into widgets.rs 2025-08-11 23:40:52 -05:00
cb2b57449a Create a "widgets" module (by moving title scene)
The non-gameplay scenes are really just a bunch of widgets. I'm going to
put them all together and then bundle the functionality with some
exported plugin builders.
2025-08-11 23:39:42 -05:00
9a262fcffc Move Lifetime component to machinery module 2025-08-11 23:34:12 -05:00
34ee2fcc7d Create a "machinery" module for game systems
I'm not sold on the name, but anyway.

This module will hold the systems that power the main game mechanics, as
well as a few extra items to support that (in particular, the Lifetime
component).
2025-08-11 23:28:39 -05:00
93da225636 Move resources to a resources.rs submodule 2025-08-11 23:19:06 -05:00
cd194e2dbf Move collision system to physics module 2025-08-11 23:07:18 -05:00
1369a3092f Move the ship & bullet systems into the object mod 2025-08-11 23:01:14 -05:00
619037dab0 Move asteroid spawning & splitting systems
They deal with events, but are directly related to how the Asteroid
object interacts with the events, so I'm putting them here.
2025-08-11 22:59:20 -05:00
c1b69c412a autoformat 2025-08-11 22:48:08 -05:00
d8a83b77c2 Move ship & bullet to the objects module 2025-08-11 22:47:48 -05:00
f5ff7c8779 Move Asteroid components to the objects.rs mod 2025-08-11 22:44:05 -05:00
f4484f759f Move SpawnAsteroid event into events.rs 2025-08-11 19:16:34 -05:00
571b910945 Rename "event" module to be plural "events.rs" 2025-08-11 19:14:22 -05:00
804186ea2f Handle player ship destruction... some of it...
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
The player will be respawned, their lives decreased, and the board
cleared. The UI doesn't update, and the sudden snap to a freshly reset
board is quite jarring. The state transition to GameOver stops the game,
but there isn't anything else running in that state so it just looks
frozen.

Basically, there's a ton left to do, but technically I have handled
player ship destruction!
2025-08-10 21:29:25 -05:00
45b1fe751f Create the asteroid splitter to break down rocks.
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
2025-08-10 20:45:08 -05:00
3d28d489b0 Fix: Pass size through to spawned asteroid
I actually have most of the asteroid's destruction handling system done
and found this bug.

Asteroid *assets* are selected based on the size set in the spawn event,
but the `Asteroid` Component itself was left hard-coded to the smallest
size.
2025-08-10 18:46:49 -05:00
cdd665cc93 Add bullet on-impact despawning system 2025-08-10 18:43:56 -05:00
364fbd7530 Use the lifetime limiters on Bullets & Asteroids
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m3s
Closes #14

Despawn bullets to limit range.

Despawn asteroids to limit random garbage floating around the scene.
2025-08-10 17:14:26 -05:00
2f463303a0 Create Lifetime component and system
Closes #13

The lifetime component, and system to operate it, are ready! Now I can
delete things that have lived for too long.
2025-08-10 17:07:20 -05:00
8d689d7842 Wire in the bullet & asteroid destruction events 2025-08-10 16:49:22 -05:00
65f28e832f Implement basic gun controller
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m3s
The spacebar fires the gun, bullets are spawned on top of the ship with
a velocity that sends them forward (relative to the ship).

I still need a despawn mechanism, and a fire rate control. To despawn
things, I'm already planning a `Lifetime` component. For rate of fire,
an additional component will be created and attached to the player ship.
2025-08-10 13:30:42 -05:00
dea8a0dc1a Fix: apply thrust input properly
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m11s
Yay for funny coordinate spaces. I was, again, using the wrong
operations to get the 2D Cartesian angle and apply force to the ship.
2025-08-09 16:25:19 -05:00
6191fde25a Fix: apply steering input properly
The ship in Asteroids isn't expected to spin up while holding a steering
direction, but that's exactly what I just made it do.

Fix that problem by assigning, not accumulating, the angular velocity
for the ship.
2025-08-09 16:09:54 -05:00
d4f11faf5a Fix: integrate rotation *correctly*
Something something quaternions are hard. I thought I would take the two
"things", add them together, and then put them back into the transform.

That's clearly not how it works :v
2025-08-09 16:04:51 -05:00
e841facf73 Remove Rotation component, update usage sites 2025-08-09 16:04:12 -05:00
939ffc70a1 Add AngularVelocity, begin removal of Rotation
The rotation component is also redundant with Bevy's transform
component.

This new component and system fill the physics role, but the input
handling code needs to be updated.

Player steering still functions because it uses the `Rotation` component
to direct the force vector. The force is correctly applied to the linear
velocity vector. An improvement would be to have a force/impulse
accumulator so I could account for mass, but I'm not going to do that
right now.
2025-08-09 15:50:54 -05:00
877c7f93d7 Drop TODO to combine phys fns, update docstring
Replacing the `Position` component with direct manipulation of the
transform functionally completed the TODO. The functions weren't exactly
combined, but the resulting behavior might as well have been.

I've updated the docstring to (exist, actually. yay syntax) describe the
system accurately.
2025-08-09 15:26:28 -05:00
2b1a0f386e Add an angular velocity component 2025-08-09 15:14:05 -05:00
515ecaac27 autoformat 2025-08-09 15:11:57 -05:00
3922cac3d7 Finish removal of Position
The component has been completely removed, and all call sites are fixed
to use the Transform directly.
2025-08-09 15:10:44 -05:00
e834d94b8a Use Transform not Position in wrapping system 2025-08-09 15:08:15 -05:00
ad5e86a06b Begin removal of Position component
The position component is redundant with the built-in Bevy Transform.
I've updated the velocity integrator to use the transform directly.

Physics still works, but things still set their initial locations
through the Position component. I'll need to fix all those call sites.
2025-08-09 15:05:02 -05:00
3d0da6df2d Fix module-level docstring in asteroids & config
I made a comment to help me remember the purpose, but if I do it this
way `cargo doc` will render it out to the actual documentation.
2025-08-09 14:55:07 -05:00
73b97ad15c Re-order use statements, prefer crate mods first 2025-08-09 14:53:50 -05:00
61c57783f1 Split physics parts into a submodule
The physics sim bits (that aren't Rapier2d) are now in their own
submodule. I've included the `Wrapping` marker component because it
doesn't really have anywhere else to live, and it's kinda sorta related
to the physics. It controls the motion of objects... that's physics. :p

There are name collisions between Rapier2d's `Velocity` and my own, but
that's a problem for later. I've used more specific type paths where
necessary to maintain the previous behavior.

The `physics::Position` component can go away completely. It's just an
extra copy of some of the built-in `Transform` data. I'm pretty sure it
only exists because I didn't realize I could rely on directly
manipulating the transform when I started this project.
2025-08-09 14:46:56 -05:00
809810b8ce First parts of a collision event handler
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m15s
I've added a new `event` module to contain all the game's events (which
it does not. I'll collect them all later).

Using these events, the CollisionEvent listening system can watch for
any two colliders intersecting, check on what role they play (asteroid,
ship, bullet, etc), and re-emit an event for that specific thing. Each
component can then handle it's own destruction process.
2025-08-09 12:30:37 -05:00
29735e7426 Move ship parts into it's own submodule 2025-08-08 22:03:34 -05:00
ab5f489450 Enable collision sensing for bodyless entities
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
Rapier expects to have a RigidBody attached to the entity, but I do not.

I'm not going to make one, either, because the objects in a game of
Asteroids don't need collision handling the way most games do. I just
need to know if two objects have started overlapping.

According to this: https://rapier.rs/docs/user_guides/bevy_plugin/colliders#collision-groups-and-solver-groups
only one of the two objects involved needs to have the ActiveEvents and
ActiveCollisionTypes components attached, so I've placed them on the
player ship.
2025-08-06 15:21:12 -05:00
d4ceaa6312 Add Sensor component to colliders 2025-08-06 14:44:38 -05:00
f553574e3e Beginning work with collision detection
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 31s
I'm going to grab the Rapier physics library so that I don't have to do
my own collision detection mechanism. The last time I did this, I
simplified everything into circles. This time I'd like to have convex
hulls, particularly for the player ship.

Also the last time, I ended up rolling my own quadtree impl. I'm not
particularly interested in doing that again, and I'd like to learn more
of the broader Bevy ecosystem.
2025-08-06 13:05:12 -05:00
96e9376330 Autoformat before physics feature
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m47s
2025-08-06 12:32:42 -05:00
07105760f5 Bump Rust edition to 2024
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 27s
2025-07-30 22:41:43 -05:00
1555c93bed Set asteroid velocity so they move into play area
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m24s
It's functional, if not especially interesting. Forward to the next
thing!
2025-07-29 17:44:33 -05:00
2b93654491 Randomly assign asteroid spawning positions
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m23s
I need to close the circle down to touch the corners of the play area,
but this demonstrates the principle.

Next, I need to generate a velocity and "fix" it so that the asteroid
crosses through the viewport. I left a TODO about this, which I think
will work well enough. Although it might allow for some asteroids to
slip past, or bias the density in a funny way.

Oh well, it's just an Asteroids game.
2025-07-29 16:31:35 -05:00
c80ada4aa6 Add "rand" crate, store an RNG in AsteroidSpawner 2025-07-29 13:32:26 -05:00
eee039339e Asteroid spawner now uses info from event message
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
Closes #4: "Convert asteroid spawning system into an event listener"
2025-07-29 13:26:41 -05:00
04f192b62a Drop never-used import
Thanks, VSCode. I really like when you import things I'm not actually
trying to use. SMH my head.
2025-07-29 13:17:01 -05:00
2dd3b2ff61 Fix case on AsteroidSize enum variants
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m28s
Closes #9: "Fix case on AsteroidSize enum variants"
2025-07-29 13:15:54 -05:00
2c43bc699e Begin work on event-based asteroid spawning
The events are being emitted by the spawn manager, and consumed by the
spawn_asteroid system. Now to wire in the spawn properties, and then
make a good spawning manager.
2025-07-29 13:12:22 -05:00
911b6c5fe7 Fix visibility & add constructors, program builds
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m29s
2025-07-29 12:54:09 -05:00
71ec77f5b1 Move asteroid bits to another module
Now to fix the visibility issues and make the program compile again...
2025-07-29 12:48:54 -05:00
5dfe11d31f Remove unused color import
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m30s
2025-07-29 11:59:36 -05:00
40102bf46b Drop ThrusterColors component
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m26s
I've already moved these resources to the GameAssets Resource, now I can
delete the Component struct itself.
2025-07-29 11:57:52 -05:00
0eac337c00 Update spawn_player to use new GameAssets
Some checks failed
Basic checks / Basic build-and-test supertask (push) Has been cancelled
2025-07-29 11:54:39 -05:00
3d4e0afc58 Swap asteroid-spawning to use new GameAssets 2025-07-29 11:51:12 -05:00
f62ab2c95d New GameAssets resource to hold all my assets
I'm finally getting around to centralizing all the assets instead of
letting spawners load their own.

I'm missing some assets, which may eventually be filled by textures
instead of solid-colors and simple shapes

I also need to hook up all the functions to use this thing instead.
2025-07-29 11:48:02 -05:00
6681b25728 Functional prototype of WIP asteroid spawning
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m36s
It needs a whole lot more work, but hey, look: A rock!

... well a circle, anyway.
2025-07-28 15:35:50 -05:00
68a8de1809 Make player ship wrap by marking it with Wrapping
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 3m2s
2025-07-28 09:15:23 -05:00
a6622f24b5 Add new "Wrapping" marker component
Not everything needs to wrap, so I'll use a marker component for the
ones that do. At the moment, I'm thinking only the player's ship will
wrap around. Asteroids can be de-spawned and re-spawned, and bullets can
simply evaporate.
2025-07-27 19:36:05 -05:00
c37887b0e7 Remove unused system inputs for prep widget 2025-07-27 16:20:40 -05:00
31451732c4 Finish the countdown anim with a progress bar
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 6m40s
2025-07-27 16:18:51 -05:00
4ecbfaa370 Implement (most of) the timer countdown
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 26s
The timer-wrapper thing was marked as a Component rather than a
Resource, which I have fixed.

The update function is about as straight forward as can be:
1. tick the timer
2. read the value out, format it for display,
3. check if the timer is expired, change states if so.
2025-07-27 14:42:50 -05:00
eb50655671 autoformat 2025-07-27 12:57:56 -05:00
a7d54c9192 Impl "get-ready"s despawn function 2025-07-27 12:57:07 -05:00
fccd2e6a8b Impl the "get-ready" widget's spawn function 2025-07-27 12:56:42 -05:00
efabcbf636 Start submodule to impl the "Get ready" spinner 2025-07-27 11:58:58 -05:00
f848de6b2e Replace usage of another deprecated function
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 29s
2025-07-27 11:08:59 -05:00
e605bbf80d Spawn just one camera (it's messing with egui)
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 27s
The egui debug inspector disappears when switching scenes, which seems
to be related to the camera change. I'm not going to dig into why
exactly this is happening. I'll just create one camera and keep it.
2025-07-27 11:05:49 -05:00
39bddf1c9e Fix: only run space-to-start when on title screen 2025-07-27 10:43:28 -05:00
477460ad2f Fix: Mark the main-menu camera so it despawns
The camera spawned for the main menu wasn't given the TitleUI marker
component, so it wouldn't despawn when changing to the game scene.
2025-07-27 10:41:00 -05:00
c11322969c Finally impl the "space to start" feature 2025-07-27 10:40:37 -05:00
7123192271 Implement the main menu despawn function 2025-07-27 10:33:53 -05:00
9a2381249f autoformat 2025-07-27 10:31:24 -05:00
f68d841e52 Switch to non-deprecated .single_mut() method 2025-07-27 10:31:12 -05:00
88db8a868a Make the Lives(i32) resource appear on debug UI 2025-07-27 10:30:11 -05:00
584a30f7f8 Add bevy-inspector-egui so I can fiddle with values easier 2025-07-27 09:45:33 -05:00
430b77be2e Fix: add game entities only when in Playing state 2025-07-27 09:32:49 -05:00
6eb69f476f Split title screen into it's own mod & Plugin
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 28s
2025-07-27 09:31:09 -05:00
a4409cb946 Bump to Bevy 0.16 2025-07-26 19:38:49 -05:00
38fbc85505 Autoformat 2025-07-26 18:59:56 -05:00
08c9625e71 Remove all usage of old Mesh & Material bundles 2025-07-26 18:57:47 -05:00
96aff4ae46 Chain method calls, drop intermediate vars 2025-07-26 18:47:18 -05:00
a52311eac6 Switch to new Camera2d struct over cam bundle 2025-07-26 18:45:02 -05:00
cf678f9f16 Update spawn_screen function 2025-07-26 18:44:10 -05:00
2f9afaeac1 Replace spawn_ui implementation 2025-07-26 18:30:38 -05:00
7f5a166f10 Hack to get ship meshes back in place 2025-07-26 18:19:50 -05:00
5e6440340f Rename time elapsed method usage 2025-07-26 18:01:06 -05:00
290aab45f5 Bump to Bevy 0.15, enable dynamic linkage
The dynamic linkage is for improving testing cycle time, not for any direct impl reason.
2025-07-26 17:55:22 -05:00
406e611e31 Autoformat to make the checker happy
Some checks failed
Basic checks / Basic build-and-test supertask (push) Failing after 44s
2025-02-01 17:28:37 -06:00
c86cd0d642 States, I guess. Now to do the others
Game states are named and used to toggle behavior. Now to rewrite those
things to do the *right* behavior.
2024-11-29 16:45:52 -06:00
f114203665 Title menu, but always present. Time for states!
I've made a quick title menu, but it is always present. I'll need to set
up some game state stuff so I can flip between play modes.
2024-11-29 16:01:23 -06:00
37d7c1db42 Spawning score and lives UI elements, no logic
I have basic UI elements! They can't be updated, yet, and there's still
no game logic to allow the player to affect it on their own.
2024-11-28 11:56:42 -06:00
22 changed files with 8919 additions and 153 deletions

4
.cargo/config.toml Normal file
View File

@@ -0,0 +1,4 @@
[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"
rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""]

1
.gitignore vendored
View File

@@ -1 +1,2 @@
/target
/out

6640
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,35 @@
[package]
name = "asteroids"
version = "0.1.0"
edition = "2021"
version = "0.6.0-dev3"
edition = "2024"
license = "AGPL-3.0-only"
[dependencies]
bevy = "0.14.2"
bevy = "0.17"
bevy-inspector-egui = "0.34"
bevy_rapier2d = "0.32"
rand = "0.9"
[features]
default = ["dynamic_linking"]
dynamic_linking = ["bevy/dynamic_linking"]
debug_ui = ["bevy_rapier2d/debug-render-2d"]
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.3", features = ["wasm_js"] }
[profile.speedy]
inherits = "release"
codegen-units = 1
lto = "fat"
opt-level = 3
strip = "symbols"
panic = "abort"
[profile.tiny]
inherits = "release"
codegen-units = 1
lto = "fat"
opt-level = "z"
strip = "symbols"
panic = "abort"

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM rust:1.89 AS builder
RUN rustup target add wasm32-unknown-unknown
RUN cargo install --locked wasm-bindgen-cli
COPY . .
RUN make -j
FROM busybox:musl
RUN mkdir -p /var/www
COPY --from=builder ./out/ /var/www
WORKDIR /var/www
# TODO: Make httpd accept interrupt signals so the container exits properly.
# (<ctrl>+c and `docker stop ...` don't work because Busybox doesn't answer)
CMD ["httpd", "-f", "-p", "8080"]

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

72
Makefile Normal file
View File

@@ -0,0 +1,72 @@
##
## This Makefile exists to produce WASM builds.
## Do not use it if that isn't your goal!
##
# Patch these to select a different build profile or target
# The target shouldn't change any time soon. WASM64, I guess. Other targets
# aren't aimed at the web, so you shouldn't be using this makefile.
CARGO_TARGET := wasm32-unknown-unknown
CARGO_PROFILE := tiny
SRC_DIR = ./src
SRCS := $(wildcard $(SRC_DIR)/**)
.PHONY: clean full-clean tarball tarball-standalone web web-standalone
# "Standalone" version. It includes an index.html to serve as-is
web-standalone: out/asteroids.js out/asteroids_bg.wasm.gz out/index.html
# "Bundle-able" version. It has a page, but no index.html. Consumers are
# expected to provide their own index.html and link to this page.
web: out/asteroids.js out/asteroids_bg.wasm.gz out/asteroids.html
tarball: asteroids_web_root.tar
tarball_standalone: asteroids_web_root_standalone.tar
asteroids_web_root.tar: out/asteroids.js out/asteroids_bg.wasm.gz out/asteroids.html
tar -caf $@ $^
asteroids_web_root_standalone.tar: out/asteroids.js out/asteroids_bg.wasm.gz out/index.html
tar -caf $@ $^
target/$(CARGO_TARGET)/$(CARGO_PROFILE)/asteroids.wasm: $(SRCS) Cargo.lock Cargo.toml
cargo build --profile $(CARGO_PROFILE) --target $(CARGO_TARGET)
out:
mkdir $@
# Both the JS and WASM files are generated by the wasm-bindgen call, so both
# get to be on the target half of this recipe.
out/asteroids.js out/asteroids_bg.wasm.gz &: target/$(CARGO_TARGET)/$(CARGO_PROFILE)/asteroids.wasm | out
wasm-bindgen --no-typescript --target web --out-dir ./out/ --out-name asteroids target/$(CARGO_TARGET)/$(CARGO_PROFILE)/asteroids.wasm
gzip -9 -f out/asteroids_bg.wasm
# Copies the index page to the output dir.
out/index.html: www/index.html
cp -a $< $@
rm -f out/asteroids.html
# Like `out/index.html`, but renames the page for use in a larger site.
out/asteroids.html: www/index.html
cp -a $< $@
rm -f out/index.html
# Clean the web build, but not the Cargo cache. Cargo handles it's own caching
# and I don't want to obliterate it all the time.
clean:
rm -rf out/ asteroids_web_root.tar asteroids_web_root_standalone.tar
# Delete everything, including the Cargo build cache. In case someone needs
# this, I guess.
full-clean: clean
cargo clean
# Installation goal. It's meant to be a helper utility for moving the built
# output into the web root. Only supports the "bundle-able" mode.
install: web
install -dm0755 $(DESTDIR)
install -m0644 out/asteroids.js $(DESTDIR)/
install -m0644 out/asteroids_bg.wasm.gz $(DESTDIR)/
install -m0644 out/asteroids.html $(DESTDIR)/

14
README.md Normal file
View File

@@ -0,0 +1,14 @@
# Asteroids
*Another* Asteroids game I'm making. This time in Rust with the Bevy game engine.
## License
| File(s) | License |
|-|-|
| * | AGPLv3 |
| assets/* | CC0 |
(the most-specific match is the applicable license)
The sound files are from KenneyNL's "Sci-Fi Sounds (1.0)" pack. Find their work at [www.kenney.nl].

Binary file not shown.

Binary file not shown.

BIN
assets/laserSmall_001.ogg Normal file

Binary file not shown.

BIN
assets/thrusterFire_004.ogg Normal file

Binary file not shown.

View File

@@ -1,16 +1,32 @@
/*
Global constants used all over the program. Rather than leaving them scattered
where ever they happen to be needed, I'm concentrating them here.
*/
//! Global constants used all over the program. Rather than leaving them scattered
//! where ever they happen to be needed, I'm concentrating them here.
use bevy::color::Color;
pub const WINDOW_SIZE: bevy::prelude::Vec2 = bevy::prelude::Vec2::new(800.0, 600.0);
pub const WINDOW_SIZE: (u32, u32) = (800, 600);
pub(crate) const BACKGROUND_COLOR: Color = Color::srgb(0.3, 0.3, 0.3);
pub const UI_BUTTON_NORMAL: Color = Color::srgb(0.15, 0.15, 0.15); // Button color when it's just hanging out
pub const UI_BUTTON_HOVERED: Color = Color::srgb(0.25, 0.25, 0.25); // ... when it's hovered
pub const UI_BUTTON_PRESSED: Color = Color::srgb(0.55, 0.55, 0.55); // ... when it's pressed
pub(crate) const BACKGROUND_COLOR: Color = Color::srgb(0.1, 0.1, 0.1);
pub(crate) const PLAYER_SHIP_COLOR: Color = Color::srgb(1.0, 1.0, 1.0);
pub(crate) const SHIP_THRUSTER_COLOR_ACTIVE: Color = Color::srgb(1.0, 0.2, 0.2);
pub(crate) const SHIP_THRUSTER_COLOR_INACTIVE: Color = Color::srgb(0.5, 0.5, 0.5);
pub(crate) const SHIP_FIRE_RATE: f32 = 3.0; // in bullets-per-second
pub(crate) const ASTEROID_SMALL_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
pub(crate) const ASTEROID_MEDIUM_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
pub(crate) const ASTEROID_LARGE_COLOR: Color = Color::srgb(0.6, 0.6, 0.6);
pub(crate) const BULLET_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
// TODO: asteroid medium & large
pub(crate) const SHIP_THRUST: f32 = 1.0;
pub(crate) const SHIP_ROTATION: f32 = 0.1; // +/- rotation speed in... radians per frame
pub(crate) const SHIP_THRUST: f32 = 4.0;
pub(crate) const SHIP_ROTATION: f32 = 4.0; // +/- rotation speed in... radians per frame
pub(crate) const BULLET_SPEED: f32 = 500.0;
pub(crate) const BULLET_LIFETIME: f32 = 2.0;
pub(crate) const ASTEROID_LIFETIME: f32 = 40.0;
pub(crate) const DEBRIS_LIFETIME: f32 = 3.0; // lifetime, in seconds
pub const RNG_SEED: [u8; 32] = *b"12345678909876543210123456789098";

View File

@@ -1,111 +1,138 @@
//! Asteroids, implemented as a Bevy plugin.
//!
//! Compile-time configurables can be found in the [`config`] module.
pub mod config;
mod machinery;
mod messages;
mod objects;
mod physics;
mod resources;
mod widgets;
use crate::config::{BACKGROUND_COLOR, PLAYER_SHIP_COLOR, SHIP_ROTATION, SHIP_THRUST, WINDOW_SIZE};
use crate::config::{
ASTEROID_LARGE_COLOR, ASTEROID_MEDIUM_COLOR, ASTEROID_SMALL_COLOR, BACKGROUND_COLOR,
BULLET_COLOR, BULLET_LIFETIME, BULLET_SPEED, PLAYER_SHIP_COLOR, SHIP_ROTATION, SHIP_THRUST,
SHIP_THRUSTER_COLOR_ACTIVE, SHIP_THRUSTER_COLOR_INACTIVE,
};
use crate::machinery::AsteroidSpawner;
use crate::objects::{Bullet, Ship, Weapon};
use crate::physics::AngularVelocity;
use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
use config::{SHIP_THRUSTER_COLOR_ACTIVE, SHIP_THRUSTER_COLOR_INACTIVE};
use bevy::prelude::*;
use bevy_rapier2d::{
plugin::{NoUserData, RapierPhysicsPlugin},
prelude::*,
};
use machinery::Lifetime;
use resources::{GameAssets, Lives, Score, WorldSize};
/// The main game plugin.
pub struct AsteroidPlugin;
impl Plugin for AsteroidPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, (spawn_camera, spawn_player))
.insert_resource(ClearColor(BACKGROUND_COLOR))
.insert_resource(WorldSize {
width: WINDOW_SIZE.x,
height: WINDOW_SIZE.y,
})
.add_systems(
FixedUpdate,
(input_ship_thruster, input_ship_rotation, wrap_entities),
app.add_plugins((
widgets::PluginGameMenu,
widgets::PluginGameOver,
widgets::PluginGetReady,
widgets::PluginGameHud,
RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(10.0),
))
.insert_resource(ClearColor(BACKGROUND_COLOR))
.insert_resource(WorldSize::default())
.insert_resource(Lives(3))
.register_type::<Lives>()
.insert_resource(Score(0))
.register_type::<Score>()
.insert_resource(AsteroidSpawner::new())
.init_resource::<GameAssets>()
.add_systems(Startup, spawn_camera)
.add_systems(OnEnter(GameState::Playing), objects::spawn_player)
.add_systems(OnExit(GameState::Playing), despawn::<Ship>)
.add_systems(
FixedUpdate,
(
input_ship_thruster,
input_ship_rotation,
input_ship_shoot,
physics::wrap_entities,
machinery::tick_asteroid_manager,
machinery::operate_sparklers,
objects::spawn_asteroid.after(machinery::tick_asteroid_manager),
objects::split_asteroids,
objects::bullet_impact_listener,
objects::ship_impact_listener,
physics::collision_listener,
machinery::tick_lifetimes,
machinery::update_scoreboard,
)
.add_systems(
FixedPostUpdate,
(integrate_velocity, update_positions, apply_rotation_to_mesh),
);
.run_if(in_state(GameState::Playing)),
)
.add_systems(
FixedPostUpdate,
(
physics::integrate_velocity,
physics::integrate_angular_velocity,
)
.run_if(in_state(GameState::Playing)),
)
.add_message::<messages::SpawnAsteroid>()
.add_message::<messages::AsteroidDestroy>()
.add_message::<messages::ShipDestroy>()
.add_message::<messages::BulletDestroy>();
app.insert_state(GameState::TitleScreen);
}
}
#[derive(Component)]
struct Position(bevy::math::Vec2);
/// Despawns entities matching the generic argument. Intended to remove UI
/// elements.
pub(crate) fn despawn<T: Component>(mut commands: Commands, to_despawn: Query<Entity, With<T>>) {
for entity in to_despawn {
commands.entity(entity).despawn();
}
}
#[derive(Component)]
struct Velocity(bevy::math::Vec2);
#[derive(Component)]
struct Rotation(f32);
#[derive(Component)]
struct Ship;
// Data component to store color properties attached to an entity
// This was easier (and imo better) than holding global consts with
// UUID assets.
#[derive(Component)]
struct ThrusterColors(Handle<ColorMaterial>, Handle<ColorMaterial>);
#[derive(Resource)]
struct WorldSize {
width: f32,
height: f32,
/// The game's main state tracking mechanism, registered with Bevy as a [`State`](`bevy::prelude::State`).
#[derive(Clone, Debug, Eq, Hash, PartialEq, States)]
pub enum GameState {
TitleScreen, // Program is started. Present title screen and await user start
GetReady, // Short timer to let the player get ready after pressing start
Playing, // Player has started the game. Run the main loop
GameOver, // Game has ended. Present game over dialogue and await user restart
}
fn spawn_camera(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
commands.spawn(Camera2d);
}
fn spawn_player(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
let triangle = Triangle2d::new(
Vec2::new(0.5, 0.0),
Vec2::new(-0.5, 0.45),
Vec2::new(-0.5, -0.45),
);
let thruster_firing_id = materials.add(SHIP_THRUSTER_COLOR_ACTIVE);
let thruster_stopped_id = materials.add(SHIP_THRUSTER_COLOR_INACTIVE);
let ship_mesh = MaterialMesh2dBundle {
mesh: meshes.add(triangle).into(),
material: materials.add(PLAYER_SHIP_COLOR),
transform: Transform::default().with_scale(Vec3::new(20.0, 20.0, 20.0)),
..default()
};
let thruster_mesh = MaterialMesh2dBundle {
mesh: meshes.add(triangle).into(),
material: materials.add(PLAYER_SHIP_COLOR),
transform: Transform::default()
.with_scale(Vec3::splat(0.5))
.with_translation(Vec3::new(-0.5, 0.0, -0.1)),
..default()
};
let thruster = commands.spawn(thruster_mesh).id();
let mut ship_id = commands.spawn((
Ship,
Position(Vec2::default()),
Velocity(Vec2::ZERO),
Rotation(0.0),
ship_mesh,
ThrusterColors(thruster_firing_id, thruster_stopped_id),
));
ship_id.add_child(thruster);
}
/*
Checks if "W" is pressed and increases velocity accordingly.
*/
/// Player's thruster control system.
///
/// Checks if "W" is pressed and increases velocity accordingly.
fn input_ship_thruster(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut query: Query<(&mut Velocity, &Rotation, &mut Children, &ThrusterColors), With<Ship>>,
mut query: Query<
(
&mut physics::Velocity,
&Transform,
Option<&mut AudioSink>,
&mut Children,
),
With<Ship>,
>,
mut commands: Commands,
game_assets: Res<GameAssets>,
) {
let Ok((mut velocity, rotation, children, colors)) = query.get_single_mut() else {
// TODO: Maybe change for a Single<Ship>> so this only runs for the one ship
// buuut... that would silently do nothing if there are 0 or >1 ships, and
// I might want to crash on purpose in that case.
//
// The AudioSink component doesn't exist for just one frame, forcing it to
// be an optional system parameter. I'm not sure if I want to guard it with
// a check like it does now, or finally switch to using a Single<...> query
// parameter. I would lose ship control if the sound sink didn't spawn, but
// that should be fine -- any time that fails, more has likely also failed.
let Ok((mut velocity, transform, audio, children)) = query.single_mut() else {
let count = query.iter().count();
panic!("There should be exactly one player ship! Instead, there seems to be {count}.");
};
@@ -115,75 +142,85 @@ fn input_ship_thruster(
.expect("Couldn't find first child, which should be the thruster");
if keyboard_input.pressed(KeyCode::KeyW) {
velocity.0 += Vec2::from_angle(rotation.0) * SHIP_THRUST;
commands.entity(*thrusters).insert(colors.0.clone());
velocity.0 += (transform.rotation * Vec3::X).xy() * SHIP_THRUST;
commands
.entity(*thrusters)
.insert(MeshMaterial2d(game_assets.thruster_mat_active()));
if let Some(audio) = audio {
audio.play();
}
} else {
commands.entity(*thrusters).insert(colors.1.clone());
commands
.entity(*thrusters)
.insert(MeshMaterial2d(game_assets.thruster_mat_inactive()));
if let Some(audio) = audio {
audio.pause();
}
}
}
/*
Checks if "A" or "D" is pressed and updates the player's Rotation component accordingly
Does *not* rotate the graphical widget! (that's done by the `apply_rotation_to_mesh` system)
*/
/// Player's rotation control system.
///
/// Checks if "A" or "D" is pressed and updates the player's [`AngularVelocity`]
/// component accordingly.
fn input_ship_rotation(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut query: Query<&mut Rotation, With<Ship>>,
mut query: Query<&mut AngularVelocity, With<Ship>>,
) {
let Ok(mut rotation) = query.get_single_mut() else {
let Ok(mut angular_vel) = query.single_mut() else {
let count = query.iter().count();
panic!("There should be exactly one player ship! Instead, there seems to be {count}.");
};
if keyboard_input.pressed(KeyCode::KeyA) {
rotation.0 += SHIP_ROTATION;
angular_vel.0 = SHIP_ROTATION;
} else if keyboard_input.pressed(KeyCode::KeyD) {
rotation.0 -= SHIP_ROTATION;
angular_vel.0 = -SHIP_ROTATION;
} else {
angular_vel.0 = 0.0;
}
}
/*
Add velocity to position
*/
fn integrate_velocity(mut query: Query<(&mut Position, &Velocity)>, time: Res<Time>) {
for (mut position, velocity) in &mut query {
position.0 += velocity.0 * time.delta_seconds();
}
}
fn update_positions(mut query: Query<(&mut Transform, &Position)>) {
for (mut transform, position) in &mut query {
transform.translation.x = position.0.x;
transform.translation.y = position.0.y;
}
}
/*
Assigns the rotation to the transform by copying it from the Rotation component.
*/
fn apply_rotation_to_mesh(mut query: Query<(&mut Transform, &Rotation)>) {
for (mut transform, rotation) in &mut query {
transform.rotation = Quat::from_rotation_z(rotation.0);
}
}
fn wrap_entities(mut query: Query<&mut Position>, world_size: Res<WorldSize>) {
let right = world_size.width / 2.0;
let left = -right;
let top = world_size.height / 2.0;
let bottom = -top;
for mut pos in query.iter_mut() {
if pos.0.x > right {
pos.0.x = left;
} else if pos.0.x < left {
pos.0.x = right;
}
if pos.0.y > top {
pos.0.y = bottom;
} else if pos.0.y < bottom {
pos.0.y = top;
}
/// Player's gun trigger.
///
/// Checks if the spacebar has just been pressed, spawning a bullet if so.
///
/// TODO: Hook up a timer to control weapon fire-rate. Something will have to
/// tick those timers. Maybe this system?
fn input_ship_shoot(
keyboard_input: Res<ButtonInput<KeyCode>>,
ship: Single<(&Transform, &physics::Velocity, &mut Weapon), With<Ship>>,
game_assets: Res<GameAssets>,
mut commands: Commands,
time: Res<Time>,
) {
let (ship_pos, ship_vel, mut weapon) = ship.into_inner();
// Tick the timer so the cooldown eventually finishes. Once it does, the
// value will clamp at 0. The weapon is now ready.
weapon.tick(time.delta());
// If the weapon is ready and the player presses the trigger,
// spawn a bullet & reset the timer.
if weapon.is_finished() && keyboard_input.pressed(KeyCode::Space) {
weapon.reset();
// Derive bullet velocity, add to the ship's velocity
let bullet_vel = (ship_pos.rotation * Vec3::X).xy() * BULLET_SPEED;
let bullet_vel = bullet_vel + ship_vel.0;
commands.spawn((
Bullet,
Collider::ball(0.2),
Sensor,
ActiveEvents::COLLISION_EVENTS,
ActiveCollisionTypes::STATIC_STATIC,
physics::Velocity(bullet_vel),
Mesh2d(game_assets.bullet().0),
MeshMaterial2d(game_assets.bullet().1),
ship_pos.clone(), // clone ship transform
Lifetime(Timer::from_seconds(BULLET_LIFETIME, TimerMode::Once)),
AudioPlayer::new(game_assets.laser_sound()),
PlaybackSettings::ONCE, // `Lifetime` already despawns the entity, so this doesn't need to
));
}
}

154
src/machinery.rs Normal file
View File

@@ -0,0 +1,154 @@
//! Systems, Components, and any other items for powering the game logic.
//!
//! Where the objects (ship, asteroid, etc) carry their own behavioral systems,
//! the *game* keeps its main logic here. Its for ambient behaviors, like
//! asteroid spawning, or eventually the flying saucer spawns.
use rand::{Rng, SeedableRng};
use std::time::Duration;
use bevy::prelude::*;
use crate::{
WorldSize,
messages::{AsteroidDestroy, SpawnAsteroid},
objects::AsteroidSize,
resources::Score,
};
/// Asteroid spawning parameters and state.
///
/// This struct keeps track of the rng and timer for spawning asteroids. In the
/// future it may contain additional fields to allow for more control.
///
/// It's values are operated by the [`tick_asteroid_manager`] system.
#[derive(Resource)]
pub struct AsteroidSpawner {
rng: std::sync::Mutex<rand::rngs::StdRng>,
timer: Timer,
// TODO: Configurables?
// - interval
// - density
// - size distribution
}
impl AsteroidSpawner {
pub fn new() -> Self {
Self {
rng: std::sync::Mutex::new(rand::rngs::StdRng::from_seed(crate::config::RNG_SEED)),
timer: Timer::new(Duration::from_secs(3), TimerMode::Repeating),
}
}
}
/// Update the asteroid spawn timer in the [`AsteroidSpawner`] resource, and
/// spawns any asteroids that are due this frame.
pub fn tick_asteroid_manager(
mut events: MessageWriter<SpawnAsteroid>,
mut spawner: ResMut<AsteroidSpawner>,
time: Res<Time>,
play_area: Res<WorldSize>,
) {
spawner.timer.tick(time.delta());
if spawner.timer.just_finished() {
let mut rng = spawner
.rng
.lock()
.expect("Expected to acquire lock on the AsteroidSpawner's RNG field.");
// Use polar coordinate to decide where the asteroid will spawn
// Theta will be random between 0 to 2pi
let spawn_angle = rng.random_range(0.0..(std::f32::consts::PI * 2.0));
// Rho will be the radius of a circle bordering the viewport, multiplied by 1.2
// TODO: Use view diagonal to get a minimally sized circle around the play area
let spawn_distance = play_area.x.max(play_area.y) / 2.0;
// Convert polar to Cartesian, use as position
let pos = Vec2::new(
spawn_distance * spawn_angle.cos(),
spawn_distance * spawn_angle.sin(),
);
// Right now, I'm thinking I can use the opposite signs attached to the position Vec components.
// pos.x == -100, then vel.x = + <random>
// pos.x == 100, then vel.x = - <random>
// etc,
let mut vel = Vec2::new(rng.random_range(0.0..100.0), rng.random_range(0.0..100.0));
if pos.x > 0.0 {
vel.x *= -1.0;
}
if pos.y > 0.0 {
vel.y *= -1.0;
}
let size = match rng.random_range(0..=2) {
0 => AsteroidSize::Small,
1 => AsteroidSize::Medium,
2 => AsteroidSize::Large,
_ => unreachable!(),
};
events.write(SpawnAsteroid { pos, vel, size });
}
}
/// Sets a lifetime on an entity to automatically delete it after expiration.
#[derive(Component)]
pub struct Lifetime(pub Timer);
/// System to tick the [`Lifetime`] timers and despawn expired entities.
pub fn tick_lifetimes(
mut commands: Commands,
time: Res<Time>,
query: Query<(Entity, &mut Lifetime)>,
) {
for (e, mut life) in query {
life.0.tick(time.delta());
if life.0.just_finished() {
commands.entity(e).despawn();
}
}
}
/// Entities marked with this will flash. Used to make the debris field sparkle.
#[derive(Component, Deref, DerefMut)]
pub struct Sparkler(Timer);
impl Sparkler {
pub fn at_interval(period: f32) -> Self {
Self(Timer::from_seconds(period, TimerMode::Repeating))
}
}
/// Advances the timer in a sparkler, swapping between visible and invisible
/// each time the timer expires.
pub fn operate_sparklers(sparklers: Query<(&mut Visibility, &mut Sparkler)>, time: Res<Time>) {
for (mut vis, mut timer) in sparklers {
if timer.tick(time.delta()).just_finished() {
// Cycle between visible and in-visible modes (and print warning for "Inherited")
*vis = match *vis {
Visibility::Inherited => {
// I don't know when entities have this mode, so I'm going
// print a warning for a while.
eprintln!(
"->> WARN: `machinery::operate_sparklers` found an entity with Visibility::Inherited"
);
Visibility::Inherited
}
Visibility::Hidden => Visibility::Visible,
Visibility::Visible => Visibility::Hidden,
};
}
}
}
/// Event listener for adding score after an asteroid was destroyed
///
/// Refreshing the HUD element is done by [crate::widgets::operate_ui] (a private function)
pub fn update_scoreboard(
mut destroy_events: MessageReader<AsteroidDestroy>,
mut scoreboard: ResMut<Score>,
) {
for _event in destroy_events.read() {
scoreboard.0 += 100;
}
}

View File

@@ -1,16 +1,20 @@
use bevy::{prelude::*, window::WindowResolution};
use asteroids::{config::WINDOW_SIZE, AsteroidPlugin};
use asteroids::{AsteroidPlugin, config::WINDOW_SIZE};
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::WorldInspectorPlugin};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
resolution: WindowResolution::new(WINDOW_SIZE.x, WINDOW_SIZE.y),
canvas: Some("#game-canvas".to_owned()),
resolution: WindowResolution::new(WINDOW_SIZE.0, WINDOW_SIZE.1),
..default()
}),
..default()
}))
.add_plugins(AsteroidPlugin)
.add_plugins(EguiPlugin::default())
.add_plugins(WorldInspectorPlugin::new())
.run();
}

36
src/messages.rs Normal file
View File

@@ -0,0 +1,36 @@
use bevy::prelude::*;
use crate::objects::AsteroidSize;
/// Signals that the player's ship has been destroyed.
///
/// Produced by the [`fn collision_listener(...)`](`crate::physics::collision_listener`)
/// system when the player collides with an asteroid. They are consumed by [`fn ship_impact_listener(...)`](`crate::objects::ship_impact_listener`).
#[derive(Message)]
pub(crate) struct ShipDestroy;
/// Signals that a particular asteroid has been destroyed.
///
/// Produced by the [`fn collision_listener(...)`](`crate::physics::collision_listener`)
/// system when bullets contact asteroids. It is consumed by [`fn split_asteroid(...)`](`crate::objects::spawn_asteroid`)
/// system, which re-emits [spawn messages](`SpawnAsteroid`).
#[derive(Message)]
pub(crate) struct AsteroidDestroy(pub Entity);
/// Signals that an asteroid needs to be spawned and provides the parameters
/// for that action.
///
/// Produced by the [`tick_asteroid_manager(...)`](`crate::machinery::tick_asteroid_manager`)
/// system and consumed by the [`spawn_asteroid(...)`](`crate::objects::spawn_asteroid`) system.
#[derive(Message)]
pub struct SpawnAsteroid {
pub pos: Vec2,
pub vel: Vec2,
pub size: AsteroidSize,
}
/// Signals that a particular bullet has been destroyed (after it strikes an Asteroid).
///
/// TODO: Maybe use it for lifetime expiration (which is also a TODO item).
#[derive(Message)]
pub(crate) struct BulletDestroy(pub Entity);

256
src/objects.rs Normal file
View File

@@ -0,0 +1,256 @@
//! This module contains all the "things" in the game.
//!
//! Asteroids, the player's ship, and such.
use bevy::{
audio::{AudioPlayer, PlaybackSettings},
camera::visibility::Visibility,
ecs::{
component::Component,
entity::Entity,
message::{MessageReader, MessageWriter},
query::With,
system::{Commands, Query, Res, ResMut, Single},
},
math::{Vec2, Vec3, Vec3Swizzles},
mesh::Mesh2d,
prelude::{Deref, DerefMut},
sprite_render::MeshMaterial2d,
state::state::NextState,
time::{Timer, TimerMode},
transform::components::Transform,
};
use bevy_rapier2d::prelude::{ActiveCollisionTypes, ActiveEvents, Collider, Sensor};
use crate::{
AngularVelocity, GameAssets, GameState, Lives,
config::{ASTEROID_LIFETIME, DEBRIS_LIFETIME, SHIP_FIRE_RATE},
machinery::{Lifetime, Sparkler},
messages::{AsteroidDestroy, BulletDestroy, ShipDestroy, SpawnAsteroid},
physics::{Velocity, Wrapping},
};
/// The asteroid, defined entirely by [it's size](`AsteroidSize`).
#[derive(Component, Deref, DerefMut)]
pub struct Asteroid(pub AsteroidSize);
#[derive(Clone, Copy, Debug)]
pub enum AsteroidSize {
Small,
Medium,
Large,
}
impl AsteroidSize {
/// Convenience util to get the "next smallest" size. Useful for splitting
/// after collision.
pub fn next(&self) -> Option<Self> {
match self {
AsteroidSize::Small => None,
AsteroidSize::Medium => Some(AsteroidSize::Small),
AsteroidSize::Large => Some(AsteroidSize::Medium),
}
}
}
/// Marker component for the player's ship.
#[derive(Component)]
pub struct Ship;
/// The ship's gun (is just a timer)
#[derive(Component, Deref, DerefMut)]
pub struct Weapon(Timer);
/// Marker component for bullets.
#[derive(Component)]
pub struct Bullet;
/// Debris left behind after the ship is destroyed.
#[derive(Component)]
pub struct Debris;
/// Responds to [`SpawnAsteroid`] events, spawning as specified
pub fn spawn_asteroid(
mut events: MessageReader<SpawnAsteroid>,
mut commands: Commands,
game_assets: Res<GameAssets>,
) {
for spawn in events.read() {
let (mesh, material) = match spawn.size {
AsteroidSize::Small => game_assets.asteroid_small(),
AsteroidSize::Medium => game_assets.asteroid_medium(),
AsteroidSize::Large => game_assets.asteroid_large(),
};
let collider_radius = match spawn.size {
AsteroidSize::Small => 5.0,
AsteroidSize::Medium => 10.0,
AsteroidSize::Large => 20.0,
};
commands.spawn((
Asteroid(spawn.size),
Collider::ball(collider_radius),
Sensor,
Transform::from_translation(spawn.pos.extend(0.0)),
Velocity(spawn.vel),
Mesh2d(mesh),
MeshMaterial2d(material),
Lifetime(Timer::from_seconds(ASTEROID_LIFETIME, TimerMode::Once)),
));
}
}
/// Event listener for asteroid destruction events. Shrinks and multiplies
/// asteroids until they vanish.
///
/// - Large -> 2x Medium
/// - Medium -> 2x Small
/// - Small -> (despawned)
///
/// The velocity of the child asteroids is scattered somewhat, as if they were
/// explosively pushed apart.
pub fn split_asteroids(
mut destroy_events: MessageReader<AsteroidDestroy>,
mut respawn_events: MessageWriter<SpawnAsteroid>,
mut commands: Commands,
query: Query<(&Transform, &Asteroid, &Velocity)>,
game_assets: Res<GameAssets>,
) {
for event in destroy_events.read() {
if let Ok((transform, rock, velocity)) = query.get(event.0) {
let next_size = rock.0.next();
if let Some(size) = next_size {
let pos = transform.translation.xy();
let left_offset = Vec2::from_angle(0.4);
let right_offset = Vec2::from_angle(-0.4);
respawn_events.write(SpawnAsteroid {
pos,
vel: left_offset.rotate(velocity.0),
size,
});
respawn_events.write(SpawnAsteroid {
pos,
vel: right_offset.rotate(velocity.0),
size,
});
}
// Always despawn the asteroid. New ones (may) be spawned in it's
// place, but this one is gone.
commands.entity(event.0).despawn();
// Play a sound for the asteroid exploding
commands.spawn((
AudioPlayer::new(game_assets.asteroid_crack_sound()),
PlaybackSettings::DESPAWN,
));
}
}
}
/// Spawns the player at the world origin. Used during the state change to
/// [`GameState::Playing`] to spawn the player.
///
/// This only spawns the player. For player **re**-spawn activity, see the
/// [`ship_impact_listener()`] system.
pub fn spawn_player(mut commands: Commands, game_assets: Res<GameAssets>) {
commands
.spawn((
Collider::ball(0.7),
Sensor,
ActiveEvents::COLLISION_EVENTS,
ActiveCollisionTypes::STATIC_STATIC,
Ship,
Weapon(Timer::from_seconds(1.0 / SHIP_FIRE_RATE, TimerMode::Once)),
Wrapping,
Velocity(Vec2::ZERO),
AngularVelocity(0.0),
Mesh2d(game_assets.ship().0),
MeshMaterial2d(game_assets.ship().1),
Transform::default().with_scale(Vec3::new(20.0, 20.0, 20.0)),
AudioPlayer::new(game_assets.ship_thruster_sound()),
PlaybackSettings {
mode: bevy::audio::PlaybackMode::Loop,
paused: true,
..Default::default()
},
))
.with_child((
Mesh2d(game_assets.thruster_mesh()),
MeshMaterial2d(game_assets.thruster_mat_inactive()),
Transform::default()
.with_scale(Vec3::splat(0.5))
.with_translation(Vec3::new(-0.5, 0.0, -0.1)),
));
}
/// Watch for [`BulletDestroy`] events and despawn
/// the associated bullet.
pub fn bullet_impact_listener(mut commands: Commands, mut events: MessageReader<BulletDestroy>) {
for event in events.read() {
commands.entity(event.0).despawn();
}
}
/// Watch for [`ShipDestroy`] events and update game state accordingly.
///
/// One life is taken from the counter, asteroids are cleared, and the player
/// is placed back at the origin. If lives reach 0, this system will change
/// states to [`GameState::GameOver`].
/// - Subtract a life
/// - Check life count. If 0, go to game-over state
/// - Clear all asteroids
/// - Respawn player
pub fn ship_impact_listener(
mut events: MessageReader<ShipDestroy>,
mut commands: Commands,
mut lives: ResMut<Lives>,
rocks: Query<Entity, With<Asteroid>>,
mut player: Single<(&mut Transform, &mut Velocity), With<Ship>>,
mut next_state: ResMut<NextState<GameState>>,
game_assets: Res<GameAssets>,
) {
for _ in events.read() {
// STEP 1: Clear asteroids
for rock in rocks {
commands.entity(rock).despawn();
}
// STEP 2: Decrement lives
if lives.0 == 0 {
// If the player has run out, return early with a state change.
next_state.set(GameState::GameOver);
return;
} else {
// Decrease life count.
lives.0 -= 1;
}
// STEP 3: spawn the debris field where the player used to be.
for i in 0..10 {
let angle_rads = (i as f32) / 10.0 * std::f32::consts::TAU;
let dir = Vec2::from_angle(angle_rads);
let vel = player.1.0 + dir * 100.0;
commands.spawn((
Debris,
Visibility::Visible, // make sure it's "visible" not "Inherited" so the cycle works right
Lifetime(Timer::from_seconds(DEBRIS_LIFETIME, TimerMode::Once)),
Sparkler::at_interval(0.15),
Mesh2d(game_assets.thruster_mesh()), // borrow the thruster mesh for now
MeshMaterial2d(game_assets.thruster_mat_active()), // ... and the active thruster material
player.0.clone(), // clone the player transform
Velocity(vel),
));
}
// STEP 4: Respawn player (teleport them to the origin)
player.0.translation = Vec3::ZERO;
player.1.0 = Vec2::ZERO;
// STEP 5: Play crash sound
commands.spawn((
AudioPlayer::new(game_assets.wreck_sound()),
PlaybackSettings::DESPAWN, // despawn this entity when playback ends.
));
}
}

140
src/physics.rs Normal file
View File

@@ -0,0 +1,140 @@
//! Custom physics items
//!
//! TODO: Refactor in terms of Rapier2D, *or* implement colliders and remove it.
//!
//! Position, both translation and rotation, are tracked by the built-in
//! Bevy [`Transform`] component. This module adds a (Linear) [`Velocity`] and
//! [`AngularVelocity`] component to the mix.
//! These two components are operated by simple integrator systems to
//! accumulate translation and rotation from the velocities.
//!
//! The [`Wrapping`] component marks things that should wrap around the world
//! boundaries. It's a kind of physical property of this world, so I'm putting
//! it here.
//!
//! Collisions are also considered physics. After all, I got *a physics engine*
//! to detect them for me (so that I don't have to write clipping code).
use crate::{
WorldSize, messages,
objects::{Asteroid, Bullet, Ship},
};
use bevy::prelude::*;
use bevy_rapier2d::pipeline::CollisionEvent;
#[derive(Clone, Component)]
pub(crate) struct Velocity(pub(crate) bevy::math::Vec2);
#[derive(Component)]
pub(crate) struct AngularVelocity(pub(crate) f32);
/// Marker for any entity that should wrap on screen edges
#[derive(Component)]
pub(crate) struct Wrapping;
/// Integrate linear velocity and update the entity's transform.
pub(crate) fn integrate_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
for (mut transform, velocity) in &mut query {
let delta = velocity.0 * time.delta_secs();
transform.translation += delta.extend(0.0);
}
}
/// Integrate angular velocity and update the entity's transform.
pub(crate) fn integrate_angular_velocity(
mut objects: Query<(&mut Transform, &AngularVelocity)>,
time: Res<Time>,
) {
for (mut transform, ang_vel) in &mut objects {
let delta = ang_vel.0 * time.delta_secs();
transform.rotate_z(delta);
}
}
pub(crate) fn wrap_entities(
mut query: Query<&mut Transform, With<Wrapping>>,
world_size: Res<WorldSize>,
) {
let right = world_size.x / 2.0;
let left = -right;
let top = world_size.y / 2.0;
let bottom = -top;
for mut pos in query.iter_mut() {
if pos.translation.x > right {
pos.translation.x = left;
} else if pos.translation.x < left {
pos.translation.x = right;
}
if pos.translation.y > top {
pos.translation.y = bottom;
} else if pos.translation.y < bottom {
pos.translation.y = top;
}
}
}
/// The collision event routing system.
///
/// When a `CollisionEvent` occurrs, this system checks which things collided
/// and emits secondary events accordignly.
///
/// | Objects | Response |
/// |-|-|
/// | Ship & Asteroid | emits event [`ShipDestroy`](`crate::events::ShipDestroy`) |
/// | Asteroid & Bullet | emits event [`AsteroidDestroy`](`crate::events::AsteroidDestroy`) |
/// | Asteroid & Asteroid | Nothing. Asteroids won't collide with each other |
/// | Bullet & Bullet | Nothing. Bullets won't collide with each other (and probably can't under normal gameplay conditions) |
/// | Bullet & Ship | Nothing. The player shouldn't be able to shoot themselves (and the Flying Saucer hasn't been impl.'d, so it's bullets don't count) |
pub fn collision_listener(
mut collisions: MessageReader<CollisionEvent>,
mut ship_writer: MessageWriter<messages::ShipDestroy>,
mut asteroid_writer: MessageWriter<messages::AsteroidDestroy>,
mut bullet_writer: MessageWriter<messages::BulletDestroy>,
player: Single<Entity, With<Ship>>,
bullets: Query<&Bullet>,
rocks: Query<&Asteroid>,
) {
for event in collisions.read() {
if let CollisionEvent::Started(one, two, _flags) = event {
// Valid collisions are:
//
// - Ship & Asteroid
// - Bullet & Asteroid
//
// Asteroids don't collide with each other, bullets don't collide
// with each other, and bullets don't collide with the player ship.
// Option 1: Ship & Asteroid
if *one == *player {
if rocks.contains(*two) {
// player-asteroid collision
dbg!("Writing ShipDestroy event");
ship_writer.write(messages::ShipDestroy);
} // else, we don't care
} else if *two == *player {
if rocks.contains(*one) {
dbg!("Writing ShipDestroy event");
ship_writer.write(messages::ShipDestroy);
}
}
// Option 2: Bullet & Asteroid
if bullets.contains(*one) {
if rocks.contains(*two) {
dbg!("Writing AsteroidDestroy & BulletDestroy events");
asteroid_writer.write(messages::AsteroidDestroy(*two));
bullet_writer.write(messages::BulletDestroy(*one));
}
} else if rocks.contains(*one) {
if bullets.contains(*two) {
dbg!("Writing AsteroidDestroy & BulletDestroy events");
asteroid_writer.write(messages::AsteroidDestroy(*one));
bullet_writer.write(messages::BulletDestroy(*two));
}
}
}
}
}

210
src/resources.rs Normal file
View File

@@ -0,0 +1,210 @@
//! All the resources for the game
use bevy::{
asset::{AssetServer, Assets, Handle},
audio::AudioSource,
ecs::{
resource::Resource,
world::{FromWorld, World},
},
math::{
Vec2,
primitives::{Polyline2d, Segment2d, Triangle2d},
},
mesh::Mesh,
prelude::{Deref, DerefMut, Reflect, ReflectResource},
sprite_render::ColorMaterial,
};
use bevy_inspector_egui::InspectorOptions;
use bevy_inspector_egui::inspector_options::ReflectInspectorOptions;
use crate::{
ASTEROID_LARGE_COLOR, ASTEROID_MEDIUM_COLOR, ASTEROID_SMALL_COLOR, BULLET_COLOR,
PLAYER_SHIP_COLOR, SHIP_THRUSTER_COLOR_ACTIVE, SHIP_THRUSTER_COLOR_INACTIVE,
config::WINDOW_SIZE,
};
#[derive(InspectorOptions, Reflect, Resource, Debug, Deref, Clone, Copy)]
#[reflect(Resource, InspectorOptions)]
pub struct Score(pub i32);
impl From<Score> for String {
fn from(value: Score) -> Self {
value.to_string()
}
}
#[derive(InspectorOptions, Reflect, Resource, Debug, Deref, Clone, Copy)]
#[reflect(Resource, InspectorOptions)]
pub struct Lives(pub i32);
impl From<Lives> for String {
fn from(value: Lives) -> Self {
value.to_string()
}
}
// TODO: consider switching this to use a u32 pair like the Window settings
// thing now does.
#[derive(Deref, DerefMut, Resource)]
pub struct WorldSize(Vec2);
impl Default for WorldSize {
fn default() -> Self {
WorldSize(Vec2::new(WINDOW_SIZE.0 as f32, WINDOW_SIZE.1 as f32))
}
}
#[derive(Resource)]
pub struct GameAssets {
meshes: [Handle<Mesh>; 5],
materials: [Handle<ColorMaterial>; 7],
sounds: [Handle<AudioSource>; 4],
}
impl GameAssets {
pub fn ship(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
(self.meshes[0].clone(), self.materials[0].clone())
}
// The thruster mesh is actually just the ship mesh
pub fn thruster_mesh(&self) -> Handle<Mesh> {
self.meshes[0].clone()
}
// TODO: Look into parameterizing the material
// A shader uniform should be able to do this, but I don't know how to
// load those in Bevy.
pub fn thruster_mat_inactive(&self) -> Handle<ColorMaterial> {
self.materials[1].clone()
}
pub fn thruster_mat_active(&self) -> Handle<ColorMaterial> {
self.materials[2].clone()
}
pub fn asteroid_small(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
(self.meshes[1].clone(), self.materials[3].clone())
}
pub fn asteroid_medium(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
(self.meshes[2].clone(), self.materials[4].clone())
}
pub fn asteroid_large(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
(self.meshes[3].clone(), self.materials[5].clone())
}
pub fn bullet(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
(self.meshes[4].clone(), self.materials[6].clone())
}
pub fn wreck_sound(&self) -> Handle<AudioSource> {
self.sounds[0].clone()
}
pub fn laser_sound(&self) -> Handle<AudioSource> {
self.sounds[1].clone()
}
pub fn asteroid_crack_sound(&self) -> Handle<AudioSource> {
self.sounds[2].clone()
}
pub fn ship_thruster_sound(&self) -> Handle<AudioSource> {
self.sounds[3].clone()
}
}
impl FromWorld for GameAssets {
fn from_world(world: &mut World) -> Self {
let mut world_meshes = world.resource_mut::<Assets<Mesh>>();
let meshes = [
world_meshes.add(Triangle2d::new(
Vec2::new(0.5, 0.0),
Vec2::new(-0.5, 0.45),
Vec2::new(-0.5, -0.45),
)),
world_meshes.add(Polyline2d::new(
[
Vec2::new(0.1, 0.0),
Vec2::new(0.8, 0.2),
Vec2::new(0.8, 0.3),
Vec2::new(0.1, 1.0),
Vec2::new(-0.5, 1.0),
Vec2::new(-0.3, 0.3),
Vec2::new(-1.0, 0.3),
Vec2::new(-1.0, -0.2),
Vec2::new(-0.5, -1.0),
Vec2::new(0.1, -0.8),
Vec2::new(0.5, -0.9),
Vec2::new(1.0, -0.4),
Vec2::new(0.1, 0.0),
]
.into_iter()
.map(|vert| vert * 5.0),
)),
world_meshes.add(Polyline2d::new(
[
Vec2::new(0.6, 0.3),
Vec2::new(1.0, 0.6),
Vec2::new(0.6, 1.0),
Vec2::new(0.1, 0.8),
Vec2::new(-0.4, 1.0),
Vec2::new(-1.0, 0.6),
Vec2::new(-0.8, -0.1),
Vec2::new(-1.0, -0.5),
Vec2::new(-0.4, -1.0),
Vec2::new(-0.3, -0.7),
Vec2::new(0.6, -1.0),
Vec2::new(1.0, -0.3),
Vec2::new(0.6, 0.3),
]
.into_iter()
.map(|vert| vert * 10.0),
)),
world_meshes.add(Polyline2d::new(
[
Vec2::new(1.0, -0.1),
Vec2::new(1.0, 0.3),
Vec2::new(0.4, 1.0),
Vec2::new(-0.2, 1.0),
Vec2::new(-0.9, 0.3),
Vec2::new(-0.5, 0.1),
Vec2::new(-0.9, -0.1),
Vec2::new(-0.5, -1.0),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, -1.0),
Vec2::new(0.5, -1.0),
Vec2::new(1.0, -0.1),
]
.into_iter()
.map(|vert| vert * 20.0),
)),
world_meshes.add(Segment2d::new(Vec2::new(-0.1, 0.0), Vec2::new(0.1, 0.0))),
];
let mut world_materials = world.resource_mut::<Assets<ColorMaterial>>();
let materials = [
world_materials.add(PLAYER_SHIP_COLOR),
world_materials.add(SHIP_THRUSTER_COLOR_INACTIVE),
world_materials.add(SHIP_THRUSTER_COLOR_ACTIVE),
world_materials.add(ASTEROID_SMALL_COLOR),
// TODO: asteroid medium and large colors
world_materials.add(ASTEROID_MEDIUM_COLOR),
world_materials.add(ASTEROID_LARGE_COLOR),
world_materials.add(BULLET_COLOR),
];
let loader = world.resource_mut::<AssetServer>();
let sounds = [
loader.load("explosionCrunch_004.ogg"),
loader.load("laserSmall_001.ogg"),
loader.load("explosionCrunch_000.ogg"),
loader.load("thrusterFire_004.ogg"),
];
GameAssets {
meshes,
materials,
sounds,
}
}
}

363
src/widgets.rs Normal file
View File

@@ -0,0 +1,363 @@
use std::ops::DerefMut;
use crate::{
GameState,
config::{UI_BUTTON_HOVERED, UI_BUTTON_NORMAL, UI_BUTTON_PRESSED},
despawn,
resources::{Lives, Score},
};
use bevy::{
color::palettes::css::{BLACK, DARK_GRAY, GREEN, LIGHT_BLUE, RED, WHITE},
prelude::*,
};
/// Plugin for the main menu
pub struct PluginGameMenu;
impl Plugin for PluginGameMenu {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(GameState::TitleScreen), spawn_menu)
.add_systems(OnExit(GameState::TitleScreen), despawn::<MarkerMainMenu>)
.add_systems(
Update,
(handle_spacebar, operate_buttons).run_if(in_state(GameState::TitleScreen)),
);
}
}
/// Plugin for the "get ready" period as gameplay starts.
pub struct PluginGetReady;
impl Plugin for PluginGetReady {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(GameState::GetReady), spawn_get_ready)
.add_systems(OnExit(GameState::GetReady), despawn::<OnReadySetGo>)
.add_systems(
Update,
(animate_get_ready_widget).run_if(in_state(GameState::GetReady)),
)
.insert_resource(ReadySetGoTimer(Timer::from_seconds(3.0, TimerMode::Once)));
}
}
/// Plugin for the in-game HUD
pub struct PluginGameHud;
impl Plugin for PluginGameHud {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(GameState::Playing), spawn_ui)
.add_systems(OnExit(GameState::Playing), despawn::<MarkerHUD>)
.add_systems(Update, (operate_ui).run_if(in_state(GameState::Playing)));
}
}
/// Plugin for the game-over screen
pub struct PluginGameOver;
impl Plugin for PluginGameOver {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(GameState::GameOver), spawn_gameover_ui)
.add_systems(OnExit(GameState::GameOver), despawn::<MarkerGameOver>)
.add_systems(
Update,
operate_buttons.run_if(in_state(GameState::GameOver)),
);
}
}
// Marker component for the title screen UI entity.
// This way, a query for the TitleUI can be used to despawn the title screen
#[derive(Component)]
struct MarkerMainMenu;
/// Marker component for things on the get-ready indicator
#[derive(Component)]
struct OnReadySetGo;
/// Marker for things on the game-over screen
#[derive(Component)]
struct MarkerGameOver;
/// Marker for things on the HUD (the in-game UI elements)
#[derive(Component)]
struct MarkerHUD;
/// Action specifier for the buttons on the menus.
///
/// Instead of holding function pointers for use as callbacks, I'm doing enum-
/// dispatch. Add a variant according to what action the button press should
/// trigger.
///
/// Only [`PluginGameMenu`] and [`PluginGameOver`] will use it to this
/// component. There is no always-on, global system.
#[derive(Component)]
enum ButtonMenuAction {
ToMainMenu,
StartGame,
Quit,
}
/// Newtype wrapper for `Timer`. Used to count down during the "get ready" phase.
#[derive(Deref, DerefMut, Resource)]
struct ReadySetGoTimer(Timer);
/// Marker for the counter text segment
#[derive(Component)]
struct CountdownText;
/// Marker for the counter bar segment
#[derive(Component)]
struct CountdownBar;
/// Utility function for creating a standard button.
fn button_bundle(text: &str) -> impl Bundle {
(
Button,
// TODO: Generic action
Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
border: UiRect::all(Val::Px(2.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(Val::Px(5.0)),
..default()
},
BorderColor::all(Color::BLACK),
BorderRadius::MAX,
BackgroundColor(UI_BUTTON_NORMAL),
children![(
Text::new(text),
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)],
)
}
fn spawn_menu(mut commands: Commands) {
commands
.spawn((
MarkerMainMenu,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
..Default::default()
},
))
.with_children(|cmds| {
cmds.spawn((
Text::new("Robert's Bad Asteroids Game"),
TextFont::from_font_size(50.0),
TextLayout::new_with_justify(Justify::Center),
TextShadow::default(),
));
cmds.spawn((
Text::new("Press space to begin"),
TextFont::from_font_size(20.0),
TextColor(Color::srgb(0.7, 0.7, 0.7)),
TextShadow::default(),
));
cmds.spawn((button_bundle("Start Game"), ButtonMenuAction::StartGame));
cmds.spawn((button_bundle("Quit"), ButtonMenuAction::Quit));
});
}
fn spawn_get_ready(mut commands: Commands, mut timer: ResMut<ReadySetGoTimer>) {
timer.reset();
commands.spawn((
OnReadySetGo, // marker, so this can be de-spawned properly
Node {
align_self: AlignSelf::Center,
justify_self: JustifySelf::Center,
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
width: Val::Percent(30.),
height: Val::Percent(30.),
..default()
},
BackgroundColor(LIGHT_BLUE.into()),
children![
(Text::new("Get Ready!"), TextColor(BLACK.into())),
(
CountdownBar,
Node {
width: Val::Percent(90.0),
height: Val::Percent(10.),
..default()
},
BackgroundColor(GREEN.into()),
),
(
CountdownText,
Text::new("<uninit timer>"),
TextColor(RED.into()),
)
],
));
}
/// Spawns the game over screen.
///
/// Used by [`PluginGameOver`] when entering the [`GameState::GameOver`] state.
fn spawn_gameover_ui(mut commands: Commands) {
commands.spawn((
MarkerGameOver, // Marker, so `despawn<T>` can remove this on state exit.
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
..default()
},
children![
(
Text::new("Game Over"),
TextFont::from_font_size(35.0),
TextShadow::default(),
),
(button_bundle("Main Menu"), ButtonMenuAction::ToMainMenu,),
(button_bundle("Quit"), ButtonMenuAction::Quit),
],
));
}
fn animate_get_ready_widget(
mut text_segment: Single<&mut Text, With<CountdownText>>,
mut bar_segment: Single<&mut Node, With<CountdownBar>>,
time: Res<Time>,
mut timer: ResMut<ReadySetGoTimer>,
mut game_state: ResMut<NextState<GameState>>,
) {
// Advance the timer, read the remaining time and write it onto the label.
timer.tick(time.delta());
// Add one to the visual value so the countdown starts at 3 and stops at 1.
// Otherwise it starts at 2 and disappears after showing 0.
// That feels wrong even though it's functionally identical.
let tval = timer.0.remaining().as_secs() + 1;
**text_segment = format!("{tval}").into();
// Shrink the progress bar Node
bar_segment.width = Val::Percent(100.0 * (1.0 - timer.fraction()));
// If the timer has expired, change state to playing.
if timer.is_finished() {
game_state.set(GameState::Playing);
}
}
/// Handles interactions with the menu buttons.
///
/// The buttons are used by the main menu and the game-over menu to change
/// between game states.
///
/// Button animation and action handling is done entirely within this system.
///
/// There are no checks for current state. If a "quit" button was put somewhere
/// on the HUD, this system would quit the game. The same will happen for
/// returning to the title screen. This should be useful for making a pause
/// menu, too.
fn operate_buttons(
mut interactions: Query<
(
&Interaction,
&mut BackgroundColor,
&mut BorderColor,
&ButtonMenuAction,
),
(Changed<Interaction>, With<Button>),
>,
mut game_state: ResMut<NextState<GameState>>,
mut app_exit_events: MessageWriter<AppExit>,
) {
// TODO: Better colors. These are taken from the example and they're ugly.
for (interaction, mut color, mut border_color, menu_action) in &mut interactions {
match *interaction {
Interaction::Pressed => {
*color = UI_BUTTON_PRESSED.into();
border_color.set_all(DARK_GRAY);
match menu_action {
ButtonMenuAction::ToMainMenu => {
game_state.set(GameState::TitleScreen);
}
ButtonMenuAction::StartGame => {
game_state.set(GameState::GetReady);
}
ButtonMenuAction::Quit => {
app_exit_events.write(AppExit::Success);
}
}
}
Interaction::Hovered => {
*color = UI_BUTTON_HOVERED.into();
border_color.set_all(WHITE);
}
Interaction::None => {
*color = UI_BUTTON_NORMAL.into();
border_color.set_all(BLACK);
}
}
}
}
/// Main menu input listener. Starts game when the spacebar is pressed.
fn handle_spacebar(input: Res<ButtonInput<KeyCode>>, mut game_state: ResMut<NextState<GameState>>) {
if input.just_pressed(KeyCode::Space) {
game_state.set(GameState::GetReady);
}
}
pub fn spawn_ui(mut commands: Commands, score: Res<Score>, lives: Res<Lives>) {
let score = score.0;
let lives = lives.0;
commands.spawn((
MarkerHUD,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Start,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect::all(Val::Px(5.0)),
..default()
},
children![
(
Text::new(format!("Score: {score}")),
TextFont::from_font_size(25.0),
TextShadow::default(),
),
(
Text::new(format!("Lives: {lives}")),
TextFont::from_font_size(25.0),
TextShadow::default(),
)
],
));
}
/// Updates the HUD with the current score & life count
///
/// TODO: some kind of event-based thing. Touching the text nodes every frame
/// seems expensive.
fn operate_ui(
mut query: Single<(&Node, &Children), With<MarkerHUD>>,
mut text_query: Query<&mut Text>,
lives: Res<Lives>,
score: Res<Score>,
) {
let (_node, children) = query.deref_mut();
let score = score.0;
let lives = lives.0;
// TODO: Something smarter than `unwrap()`
let mut score_text = text_query.get_mut(children[0]).unwrap();
**score_text = format!("Score: {score}");
let mut lives_text = text_query.get_mut(children[1]).unwrap();
**lives_text = format!("Lives: {lives}");
}

113
www/index.html Normal file
View File

@@ -0,0 +1,113 @@
<!doctype html>
<html lang="en">
<head>
<style>
body {
background-color: hsl(200, 3%, 65%);
}
h1 {
color: hsl(200, 3%, 90%);
background-color: hsl(195, 5%, 17%);
text-align: center;
margin: auto;
padding: 0.5em;
}
canvas {
margin-top: 1em;
margin-left: auto;
margin-right: auto;
display: block;
outline-color: hsl(200, 7%, 50%);
outline-style: outset;
border-radius: 8px;
background-color: rgb(40%, 40%, 40%);
}
main {
margin-left: auto;
margin-right: auto;
width: 70%;
}
table {
margin-bottom: 10px;
border-collapse: collapse;
}
th, td {
border: 1px solid;
padding: 0.1em 0.3em;
}
</style>
</head>
<body style="margin: 0px;">
<h1>
Robert's Bad Asteroids Game
</h1>
<canvas id="game-canvas" width="1280" height="720"></canvas>
<main>
<article>
<h2>Description</h2>
<p>
A (work in progress) version of the Asteroids arcade game.
</p>
</article>
<article>
<h3>Controls</h3>
<table>
<thead>
<tr>
<th scope="col">Input</th>
<th scope="col">Effect</th>
</tr>
</thead>
<tr>
<td>W</td>
<td>Fire thruster</td>
</tr>
<tr>
<td>A</td>
<td>Rotate Left</td>
</tr>
<tr>
<td>D</td>
<td>Rotate Right</td>
</tr>
<tr>
<td>Spacebar</td>
<td>Shoot gun</td>
</tr>
</table>
</article>
<article>
<h3>Misc</h3>
<table>
<tr>
<td>Source code</td>
<td><a href=https://github.com/DerVerrater/another-asteroids>https://github.com/DerVerrater/another-asteroids</a></td>
</tr>
<tr>
<td>License</td>
<td><a href="https://www.gnu.org/licenses/agpl-3.0.txt">AGPL-3.0-only</a></td>
</tr>
<tr>
<td>Program Version</td>
<!-- This version text is completely unchecked. I'll need to do something about that. -->
<td><code>v0.5.0</code></td>
</tr>
</table>
</article>
</main>
<script type="module">
import init from './asteroids.js'
let compressed = await fetch("./asteroids_bg.wasm.gz")
let wasm_stream = compressed.body.pipeThrough(new DecompressionStream("gzip"))
let blob = await new Response(wasm_stream).blob();
init(await blob.arrayBuffer()).catch((error) => {
if (!error.message.startsWith("Using exceptions for control flow, don't mind me. This isn't actually an error!")) {
throw error;
}
});
</script>
</body>
</html>