Weapon Projectiles
This content is not available in your language yet.
Making a Simple Bullet
Section titled Making a Simple Bullet-
We need a scene to spawn in, quickly setup this in a new scene:
- Area2D
- CollisionShape2D
- Sprite2D
- Area2D
-
Give it a script and connect the Area2D’s own
on_body_entered
signal to itself -
Make a new global variable inside your bullet script called
direction
. -
Make a new global constant as well, for the
SPEED
of the bullet. Your player moves at speed 300 by default, so try something around 500-700. -
In a
_physics_process(delta)
function, adddirection * speed * delta
toposition
. We multiply bydelta
because we’re manually moving the position instead of using CharacterBody2D’smove_and_slide()
function which does that for you.delta
is the time between the last physics frame and this one. -
In your function connected to the
on_body_entered
signal, enter:if body is Enemy:body.queue_free()
All in all, these will move the projectile every frame in an unspecified direction, and then when it runs into an enemy it’ll delete it.
Spawning the Bullet
Section titled Spawning the BulletWe don’t want to spawn a bullet every frame or physics frame, so we can’t use _process
or _physics_process
to spawn in a bullet.
-
Add a Timer node to your player scene.
-
In the Inspector, set the wait time to be how long you want between shots. Turn Autostart on so it starts when the game plays. Leave One Shot off so that it repeats the timer.
-
Add a script to the projectile spawner Timer node and connect its own
timeout
signal to itself. -
This is very similar to spawning in enemies. Make a new global variable in the script for the main node, in the
_ready
function set that node to your singleton’smain_node
. -
From the FileSystem dock, find and drag your bullet scene into your script, and before you release the mouse, hold ctrl/cmd.
Instructions for the rest are going to be very general, try to remember how they were implemented.
-
In your function connected to the
timeout
signal, make a new variable set to an instance of the scene. -
Get your player as a global variable for the script.
-
Back in the function, set that variable’s
direction
, or equivalent, value toplayer.velocity.normalized()
. Do the same with the projectile’s and your player’sglobal_position
. -
Then, add it as a child of your main scene’s root node.