Godot Version
4.2.2
Question
Ive been trying to implement a attack system in my code for a while now and every YouTube tutorial doesnt work out… Here’s my character body code:
extends CharacterBody2D
const SPEED = 280.0
const JUMP_VELOCITY = -399.0
@onready var sprite_2d = $AnimatedSprite2D
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
@onready var attacking = false
func _process(delta):
if Input.is_action_just_pressed(“attack”):
attack()
func attack():
var overlapping_objects = $AttackArea.get_overlapping_areas()
for area in overlapping_objects:
var parent = area.get_parent()
print(parent.name)
attacking = true
sprite_2d.animation = "Attack"
sprite_2d.play() # Added play() to ensure attack animation plays
func _physics_process(delta):
# Handle jump.
if is_on_floor() and Input.is_action_just_pressed(“jump”):
velocity.y = JUMP_VELOCITY
sprite_2d.animation = “jump”
sprite_2d.play()
# Add gravity.
if not is_on_floor():
velocity.y += gravity * delta
# Only set the jump animation if it's not already playing
if sprite_2d.animation != "jump":
sprite_2d.animation = "jump"
sprite_2d.play()
# Check horizontal movement for running animation.
if is_on_floor():
if abs(velocity.x) > 1:
sprite_2d.animation = "Run"
sprite_2d.play()
else:
sprite_2d.animation = "Idle"
sprite_2d.play()
# Get the input direction and handle the movement/deceleration.
var direction = Input.get_action_strength("right") - Input.get_action_strength("left")
velocity.x = direction * SPEED
move_and_slide()
# Update sprite flip based on movement direction.
if direction != 0:
sprite_2d.flip_h = direction < 0