Hello there,
I’m using the new canvas system to display enemies health bars.
I update the position of the canvas-image using WorldToScreenPoint and all is fine BUT the update rate of the canvas seems to be slower compared to the game update.
If I move the camera quickly, the health bars move much slower, they seems to lag (my frame-rate is good so I don’t think it’s related to frame-rate).
Any suggestion? Does the canvas actually update slower? Am I missing something?
Thank you!
Camera matrix update is delayed until very late in frame (probably updates just before rendering).
WorldToScreenPoint relies on matrix to calculate screen position.
To make it work correctly you have to do two things:
- Ensure HealthBar update is called AFTER input handling (which moves camera)
- Force Camera matrix to be updated
The code:
using UnityEngine;
public class HealthBarPositionUpdate : MonoBehaviour
{
public GameObject Enemy;
public RectTransform HealthBarElement;
// LateUpdate ensures that camera position was already updated
private void LateUpdate()
{
Camera.main.ResetWorldToCameraMatrix(); // Force camera matrix to be updated
var targetPos = Camera.main.WorldToScreenPoint(Enemy.transform.position);
if (targetPos.z > 0)
{
var pos = targetPos.Round(); // Pixel snapping
pos.z = 0;
HealthBarElement.SetPositionAndRotation(pos, Quaternion.identity);
}
}
}