Weird Visual UI problem Energy/Health/Stamina bar

Hello! So I have been trying to make an energy bar UI and I’m having issues.
I’ve made two UI images and here is the script I use:

using UnityEngine;

public class EnergyBar : MonoBehaviour {
    public PlayerMovement player;
    public float maxWidth = 180f;

    public RectTransform rt;
    public RectTransform rtBackground;
    Vector2 pos;

	// Use this for initialization
    void Start()
        pos = rt.position;
        rtBackground.position = pos;
        rtBackground.sizeDelta = new Vector2(maxWidth, 20f);

	void Update ()
        rt.sizeDelta =  new Vector2(maxWidth * player.Energy / player.maxEnergy,20f);
       rt.position = pos + new Vector2(0.5f * (rt.sizeDelta.x - maxWidth), 0f);
        Debug.Log(rt.position.x - rt.sizeDelta.x * 0.5f);
        Debug.Log(rtBackground.position.x - rtBackground.sizeDelta.x * 0.5f);

My update code is supposed to keep the left side of the energy bar at the same point. The Debug lines give me the same numbers…. However I see this on screen:

So, this is much easier if you set it up properly in the scene. Make sure you’ve got the foreground anchored to the left and set the pivot-X to zero. Then you can simply use:

rt.SetSizeWithCurrentAnchors(Axis.Horizontal, rtBackground.rect.width * percent);

RectTransform doesn’t use Transform.position.

You should be using RectTransform.anchoredPosition. That’s what’s actually controlling the position of UI.