Create a new scene with RigidBody2D as root
Add a Sprite 2D and CollisionShape2D as children
Save the scene as rock.tscn
Set the texture of the Sprite2D
Add it to the "rocks" group
Because we will be spawning different sized rocks we cannot set the collision shape in the Inspector - we must set it in code!
We want the rocks to drift in space and never stop
Ensure that Linear and Angular Damp Mode is set to Replace
Use Replace when you want precise, isolated control over an entity's friction regardless of global project defaults.
To make rocks bounce off each other
Find the Physics Material property
Add a New PhysicsMaterial
Add a script to the Rock node
screensize
size
radius
scale factor
Create a function to setup a rock when it is spawned
It Receives the starting data from the spawner and places the rock in the game world.
Whenever an asteroid spawns (or splits after being shot), the spawner tells it where to appear (_position), which way to fly (_velocity), and how big it should be (_size).
To allow asteroids to wrap around the screen
Adapt our integrate forces function from the player
To make use of the radius
To spawn rocks, the main scene will pick a random starting location. Instead of randomly picking a point along the edge of the screen we will draw a path and the script will pick a random position on our path.
In the Main scene add a Path2D node
Available in the Viewport
Add four points in a clockwise direction
I have added points tracing the outline of the viewport
Once all points are added, if it doesn't automatically close you can click on the close curve button
Add a PathFollow2D node as a child of Path2D
This will be where we spawn rocks
export a variable for the rocks scene
add a variable for the screensize
Drag the rock.tscn file into the Inspector
Create the spawn_rock function
This design pattern makes the function do double duty:
When spawning new waves, we leave them empty (null), and the function picks a random spot on the edge of the screen.
When a rock is shot and splits into smaller fragments, we can pass the exact explosion coordinates and flight angle so the pieces burst outward from where the parent rock died.
Allow the background to occupy the full screenspace
By selecting the Background node
In Offset set Centered to OFF
Play Test the game now and you will see 3 large rocks floating around the screen and they will bump off of each other and off of you!