A graph to render sine wave with custom resolution
Hello. I try to create a sine wave radar signal visualization using a line renderer component and it works well. It has it's own:
resolution (points per unit, e.g. 5 points per unit);
step (distance between each point);
total points count (depends on resolution and distance);
max spread distance (max distance for the whole wave);
current spread distance (equals the distance from the ray's origin to hit point when the ray reach and hit any tagged object).
Now I have a problem with calculating the perfect length of the whole sine wave when the ray hit an object). It is always bigger than it should be. Guys, help me please... I spent about 6 hours to try to fix that issue and I had no success. I'm done. Here's my code:
using UnityEngine;
namespace RLS
{
[RequireComponent(typeof(LineRenderer))]
public class Wave : MonoBehaviour
{
LineRenderer m_LineRenderer;
[Range(1, 255)] public float maxSpreadLength = 10;
[Range(1, 255)] public float curSpreadLength;
[Range(1, 255)] public byte resolution = 5;
public float step;
public int pointsAmount;
public float a;
public float w;
public string dispersionTag = "Dispersion";
Vector3 origin;
Vector3 direction;
RaycastHit hitInfo;
void Start()
{
m_LineRenderer = GetComponent<LineRenderer>();
}
void FixedUpdate()
{
DrawWave();
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, direction * curSpreadLength);
Gizmos.color = Color.blue;
Gizmos.DrawSphere(hitInfo.point, 1.0f);
Gizmos.color = Color.green;
Gizmos.DrawLine(transform.position, hitInfo.point);
}
public void DrawWave()
{
origin = transform.position;
direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(origin, direction, out hitInfo, maxSpreadLength) && hitInfo.transform.gameObject.tag == dispersionTag)
{
if (hitInfo.distance <= maxSpreadLength)
{
Debug.Log("D <= MAX!");
curSpreadLength = hitInfo.distance;
}
}
else
{
curSpreadLength = maxSpreadLength;
}
pointsAmount = resolution * (int)curSpreadLength;
step = curSpreadLength / (float)pointsAmount;
m_LineRenderer.positionCount = pointsAmount;
for (int i = 1; i < pointsAmount; i++)
{
float x = (float)i * step;
m_LineRenderer.SetPosition(i, new Vector3(a * Mathf.Sin(x * w), 0.0f, x));
}
}
}
}
Your answer
Follow this Question
Related Questions
Sin function returns NaN 1 Answer
Relative Position Not Constant? 0 Answers
Swimming in a sinusoidal fashion, positive cycle out of water and negative within. Am I close? 0 Answers
Detect overlapping objects 2D game 0 Answers
Instantiate And move the GameObject to the click position from another position. 1 Answer