Create a new scene with CharacterBody2D as root
Select the AnimatedSprite2D node
Add your Frames for your animation
Select the AnimatedSprite2D node
Set the Filter to Nearest
Add an instance of the Gun scene
Adjust the shoot speed and
Position the Gun appropriately
Add a script to the Player node
Create a constant for speed
Create a reference to the Gun
In the physics process function
If the shoot key is pressed
Call the shoot function
Get the direction vector
Increase velocity in the direction of the vector
Set the direction of the gun while moving
If not moving stop
Call move and slide to implement physics
Aim in the direction of the mouse cursor
Instead of passing the movement direction to the gun, we will calculate the direction from the Player's position to the Mouse's position.
Go to Project Settings => Input Map
Add an action command "fire"
Link it to the left mouse button
In the physics process after move and slide
Get the position of the mouse
Calculate the direction from the player to the mouse
NORMALIZE THE DIRECTION
Set the gun to point in that direction
If the shoot key is pressed
Call the gun's shoot function
Why do we aim after moving (move_and_slide) ?
"Usually, we put move_and_slide() last.
But for shooting, we want to be precise.
By moving first, we ensure that when we calculate the aiming angle, we are doing it from the player's final position for that frame, not their old one.
This makes the aiming feel snappy and accurate."