Godot Version
I’m using Godot 4.5
Question:
I’m a beginner and finally decided to add simple combat to my game, but I don’t know how. I’ve tried making functions but I don’t know how to link them together or if I need to do something else. I’m quite lost and most videos don’t have what I need. This is my script, please help me with my combat system.
My player also uses an animation player with a sprite 2D for the animation with keys for the hitbox(area 2D w/ CollisionShape2D).
extends CharacterBody2D
@export var SPEED := 100
const jump_force = -350
@export var Health := 3
@export var damage := 1
var is_attacking := false
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var hitbox: Area2D = $Sprite2D/Hitbox
@onready var collision_shape: CollisionShape2D = $Sprite2D/Hitbox/CollisionShape2D
func _ready() -> void:
collision_shape.disabled = true
func _physics_process(delta: float) -> void:
if not is_on_floor():
velocity += get_gravity() * delta
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = jump_force
var direction := Input.get_axis("move_left","move_right")
if direction:
velocity.x = SPEED * direction
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
#animation
if !is_attacking:
if is_on_floor() :
if velocity.x == 0:
animation_player.play("Idle")
else: animation_player.play("Walk")
else: animation_player.play("Jump")
if direction < 0:
sprite_2d.scale.x = -1
elif direction > 0: sprite_2d.scale.x = 1
if Input.is_action_just_pressed("attack"):
startattack()
func take_damage(int, damage):
Health -= damage
print("I got hit")
print(Health)
func _on_swordhit_area_entered(area: Area2D) -> void:
if area.is_in_group("enemy"):
print("I hit something!!!")
area.take_damage(damage)
func startattack():
is_attacking = true
animation_player.play("Attack")
await animation_player.animation_finished
is_attacking = false