Hi everyone, I am currently making a market exchange simulation for my game, to do this I am using line renderer in 2d, I can’t really find anything on this being a problem and like I said, in scene view it works fine.
The object the line renderer is attached to is on the UI layer and is child of a panel also on the UI layer.
Here is the script I am using, any ideas on why its not working?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MarketGraphController : MonoBehaviour
{
public LineRenderer lineRenderer;
private static float screenBottomDifference = 165f;
private static float marketHeight = 750f;
private static float marketStartPosX = 293.5f;
private static float marketStartPosY = 165f;
public static float ceiling = marketHeight + screenBottomDifference; // Maximum value
public static float floor = screenBottomDifference; // Minimum value
private static float popcornInitialValue = 4.00f;
private static float popcornCeilingValue = 13.00f;
private static float popcornFloorValue = 1.00f;
public int maxPoints = 100;
public float updateInterval = 0.1f;
public float volatility = 0.5f;
private float timeElapsed;
private float currentValue = marketHeight/((popcornCeilingValue - popcornFloorValue) / popcornInitialValue) + marketStartPosY; // Starting value
private Queue<Vector3> points = new Queue<Vector3>();
void Start()
{
if (lineRenderer == null)
{
lineRenderer = GetComponent<LineRenderer>();
}
InitializeGraph();
}
void Update()
{
timeElapsed += Time.deltaTime;
if (timeElapsed >= updateInterval)
{
timeElapsed = 0f;
UpdateGraph();
}
}
void InitializeGraph()
{
lineRenderer.positionCount = 0;
points.Clear();
Debug.Log(currentValue.ToString() + " - Current Value On Start");
AddPoint(new Vector3(marketStartPosX, currentValue, 0));
}
void UpdateGraph()
{
float changePercent = Random.Range(-volatility, volatility);
float meanValue = marketHeight/2 + screenBottomDifference; // The value around which the graph fluctuates
float meanReversionStrength = 0.1f; // Strength of the mean reversion
currentValue += currentValue * changePercent * 0.01f;
currentValue += meanReversionStrength * (meanValue - currentValue);
// Apply ceiling and floor constraints
currentValue = Mathf.Clamp(currentValue, floor, ceiling);
AddPoint(new Vector3(points.Count*20 + marketStartPosX, currentValue, 0));
}
void AddPoint(Vector3 point)
{
if (points.Count >= maxPoints)
{
points.Dequeue();
}
points.Enqueue(point);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPositions(points.ToArray());
}
}