How to Shoot Bullets in Godot

Bullet :

    For Bullet i use an Area2D Node with a Sprite Child Node And Make It a Separate Scene.


Node Placement:-
    

Bullet GDscript:-

Declare the variable for bullet speed :

    In Godot, class members can be exported. This means their value gets saved along with the resource (such as the scene) they’re attached to. They will also be available for editing in the property editor. Exporting is done by using the export keyword.
    export(int) var bulletSpeed

Bullet Movement:

Applies a local translation on the node’s X axis based on the Node Process’s delta.
    move_local_x(delta*bulletSpeed)

Detecting The Bounds Of Screen:

func is_outside_view_bounds():
return position.x>OS.get_screen_size().x or position.x<0.0\
or position.y>OS.get_screen_size().y or position.y<0.0

once bullet reach outside of the screen then destroy it. 

Godot Process function:-

func _process(delta):
if is_outside_view_bounds():
queue_free()
move_local_x(delta*bulletSpeed)

queue_free() - destroy the node

Node Signal To Detect The Collision:


Next to the “Inspector” tab is a tab labeled “Node”. Click on this tab and you’ll see all of the signals that the selected node can emit. In the case of the body_entered, the one we’re concerned with is “body_entered”. This signal is emitted  whenever the bullet physics body enters its collision shape, allowing you to know when Enemy Health reduce.
func _on_Bullet_body_entered(body):
if body.get_collision_layer_bit(2):
body.hit_by_bullet(body.position)
queue_free()

Bullet GDscript:-

Player :

Node Placement:

 spawning Bullet from position2D Node Position.

Player GDScript:

Youtube Tutorial:-😀





 

Comments