I assume you have this part under the on_message function and send it when trigger response message is received. To send the message to the correct enemy, you need to use the correct url like:
msg.post(message.other_id, "update_hp", {
hp = hp,
max_hp = max_hp
})
this will send a message to the GO you have your collision object attached to. Then, move your hp_bar script under the same root object (you will need to adjust the url for the bg and fg sprites probably). This way all scripts under the root will receive the message and you can simply check for the message from the hp_bar script.
I am giving this answer without testing so it may nnot be %100 correct but should be the direction you should go for.
Also, for script that will have many instances like enemy_stats script, it is better to have the variables on the self table, instead of using local ones. (insted of local hp, use self.hp) because the local values are shared between the GO that uses the same script. If you want your separate objects to have different stats/values make sure to use the self table as it is the table that belongs to only one GO
msg.post("hp_bar#hp_bar", "update_hp") -- should be ok
Should send the message to the correct hp_bar because you use a relative address. (Assuming you send the message from an enemy script to the hp_bar script.)
Most likely, as Asatte said, the problem is you use local variables to hold the hp value so the value is shared between all instances of the script (Lua programming in Defold).
hmmm… I think I did something wrong. I switched from local variables to self.variables
but the bug is still here. I asked chatGPT but it doesn’t help. I will appreciate if you check my project and show me my mistake tds_defold.zip (405.1 KB)
The z position of the fg sprite must be higher than the bg sprite to make sure it gets drawn on top. Currently they are both 0 and sometimes the bg gets drawn on top of fg making it look like the hp bar is empty.