Heatlhbar moves with player

Godot Version

``extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var combatmode = false

@onready var health = 100

@export var timer : Timer = null

@onready var anim = $AnimatedSprite2D

var cooldown_active : bool = false

func _ready()->void:
timer.timeout.connect(_on_timer_timeout.bind())

func _on_timer_timeout() → void:
cooldown_active = false

func _physics_process(_delta: float) → void:

if Input.is_action_just_pressed("combat"):
	print(cooldown_active)
	if cooldown_active == true:
		return
	elif combatmode == false:
		combatmode = true
		cooldown_active = true
		combat()
		timer.start()
	else:
		combatmode = false
		cooldown_active = true
		combat()
		timer.start()

if Input.is_action_just_pressed("hit"):
	punch()

look_at(get_global_mouse_position())

var directionx := Input.get_axis("left", "right")
var directiony := Input.get_axis("up", "down")

if directionx:
	velocity.x = directionx * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)
	
if directiony:
	velocity.y = directiony * SPEED
else:
	velocity.y = move_toward(velocity.y, 0, SPEED)

move_and_slide()

func combat():
if combatmode == true:
print(“hi”)
anim.play(“combat”)
else:
anim.play(“Idle”)

func punch():
if combatmode == true:
anim.play(“Punch”)

Im trying to do healthbar with player, but it rotates with the player. I tried to make the sprite look at mouse direction but it always looked 90 degrees to different location`

You may need to top-level the healthbar, or make it not a child of the player. Then you can apply only the posiiton with a RemoteTransform2D or your own script

Sounds like your sprite does not face right (0°), you may need to rotate the sprite in an image editing program

    bar.rotation = mouse_angle + (PI * 0.5) # Rotate 90 degrees ccw.

    bar.rotation = mouse_angle - (PI * 0.5) # Rotate 90 degrees cw.

I think easiest way is to change node structure. That’s how I do it in my game also.

  • Make a parent Node2D. Apply player movement (position change) to this node.
  • Make your player and healthbar node a child of this parent node.
  • Apply rotation to your player child node
Node2D (use this node to move player position)
|_ Player (use this node to rotate player)
|_ HealthBar
1 Like

I did this to always position a health bar under a spaceship:

func position_health_bar() -> void:
	# Always want the health bar under the ship
	pivot.rotation = -rotation
2 Likes

Came here to recommend this. This is my go-to node structure for game objects that require UI elements to be “attached” to them