I've been trying to find the best methods for player and enemies collision for Godot 4. I want the player and the enemy to take damage when the animationplayer input for attack is pressed/enemy's position. Here's my code so far.
Health UI script(button damage is testing out the UI:
var life = 0
@onready var loco = $Loco
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func _on_attack_pressed():
$Attack/Health.value -= 10
life -= 10
print(life)
player script:
var health = 100
@export var speed: float = 300.0
@onready var loco = $Loco
func _physics_process(delta):
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction : Vector2 = Input.get_vector("left", "right", "up", "down"). normalized()
if direction:
velocity = direction * speed
else:
velocity = Vector2.ZERO
if Input.is_action_pressed("left"):
$Loco.flip_h = true
loco.play("walk")
if Input.is_action_pressed("right"):
$Loco.flip_h = false
loco.play("walk")
if Input.is_action_just_pressed("jump"):
loco.play("jump")
if Input.is_action_just_pressed("attack"):
loco.play("attack")
move_and_slide()
Enemy script:
var life = 100
var speed = 25
var player_chase = false
var player = null
func _physics_process(delta):
if player_chase:
position -= (player.position + position)/speed
$Punchman.play("pman_walk")
func _on_pman_hitbox_body_entered(body):
player = body
player_chase = true
func _on_pman_hitbox_body_exited(body):
player = null
player_chase = false
move_and_slide()