I have a code for a dynamic crosshair:
using UnityEngine;
public class Crosshair : MonoBehaviour
{
[Range(0, 100)]
public float dilation;
public float crosshairSpeed;
public float margin, length;
public RectTransform top, bottom, left, right, center;
[SerializeField] WeaponManager weaponManager;
float marginCached,marginChanged,baseSpreadCached;
[SerializeField] Canvas canvas;
void OnGUI()
{
float topValue, bottomValue, leftValue, rightValue;
topValue = Mathf.MoveTowards(top.position.y, center.position.y + marginChanged + dilation, crosshairSpeed * Time.deltaTime);
bottomValue = Mathf.MoveTowards(bottom.position.y, center.position.y - marginChanged - dilation, crosshairSpeed * Time.deltaTime);
rightValue = Mathf.MoveTowards(right.position.x, center.position.x - marginChanged - dilation, crosshairSpeed * Time.deltaTime);
leftValue = Mathf.MoveTowards(left.position.x, center.position.x + marginChanged + dilation, crosshairSpeed * Time.deltaTime);
top.position = new Vector2(top.position.x, topValue);
bottom.position = new Vector2(bottom.position.x, bottomValue);
right.position = new Vector2(rightValue, right.position.y);
left.position = new Vector2(leftValue, left.position.y);
top.sizeDelta = new Vector2(top.sizeDelta.x, length);
bottom.sizeDelta = new Vector2(bottom.sizeDelta.x, length);
right.sizeDelta = new Vector2(length, right.sizeDelta.y);
left.sizeDelta = new Vector2(length, left.sizeDelta.y);
if (marginCached != margin || baseSpreadCached != weaponManager.weapon.baseSpread)
{
marginChanged = weaponManager.weapon.baseSpread + margin;
marginCached = margin;
baseSpreadCached = weaponManager.weapon.baseSpread;
}
dilation = weaponManager.spreadAmount;
}
}
It starts like this:
But as i move, it becomes offset from the center dot:
What’s wrong in this code, and how can i prevent this from happening?





