BasicProjectile - cluttered-code/godot-health-hitbox-hurtbox GitHub Wiki

Description

Basic projectile uses constant values and destorys itself after a collision with a HurtBox2D.

Scene

basic_projectile.tscn

[!IMPORTANT] Contains a HitBox2D to detect collisions with HurtBox2D components.

[!WARNING] In general, all sprites from projectiles to characters should look to the right for transforms to behave properly.

Basic Projectile Scene

Script

basic_projectile.gd

[!CAUTION] hit_box.ignore_collisions = true should be set when calling queue_free() to avoid collisions with other components.

class_name BasicProjectile extends Node2D

const SPEED: float = 600.0

@onready var hit_box: HitBox2D = $HitBox2D


func _ready() -> void:
	hit_box.action_applied.connect(_on_action_applied)


func _physics_process(delta: float) -> void:
	position += transform.x * SPEED * delta


func _on_action_applied(_hurt_box: HurtBox2D) -> void:
	hit_box.ignore_collisions = true
	queue_free()

Instantiate

Outside of the projectile use a Mark2D to spawn the projectile and set transform to global_transform.

func shoot():
	var projectile := basic_projectile_scene.instantiate()
	owner.add_child(projectile)
	projectile.transform = $Marker2D.global_transform