Rotate (facing mouse position) a Line Renderer used as Bezier curve
Hey there I am trying to rotate a Bezier curve following the mouse position, but the curve needs to stay at its current radius.
This is my Bezier Curve code :
public class BezierCurve : MonoBehaviour
{
public Vector3 p0;
public Vector3 p1;
public Vector3 p2;
public LineRenderer lineRenderer;
[Range(1, 64)]
public int vertexCount = 12;
private void Update()
{
List<Vector3> pointList = new List<Vector3>();
for (float ratio = 0f / vertexCount; ratio <= 1; ratio += 1.0f / vertexCount)
{
Vector3 tangentLineVertex1 = Vector3.Lerp(p0, p1, ratio);
Vector3 tangentLineVertex2 = Vector3.Lerp(p1, p2, ratio);
Vector3 bezierPoint = Vector3.Lerp(tangentLineVertex1, tangentLineVertex2, ratio);
pointList.Add(bezierPoint);
}
lineRenderer.positionCount = pointList.Count;
lineRenderer.SetPositions(pointList.ToArray());
}
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawLine(p0, p1);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(p1, p2);
Gizmos.color = Color.red;
for (float ratio = 0.5f / vertexCount; ratio < 1; ratio += 1.0f / vertexCount)
{
Gizmos.DrawLine(Vector3.Lerp(p0, p1, ratio),
Vector3.Lerp(p1, p2, ratio));
}
}
}
I tried this method on each of my point and the rotation is correct but spin in an non controllable way :
Vector2 b = Camera.main.WorldToViewportPoint(p0);
Vector2 a = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
float angle = Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
p0 = Quaternion.Euler(new Vector3(0f, 0f, angle)) * p0;
p1 = Quaternion.Euler(new Vector3(0f, 0f, angle)) * p1;
p2 = Quaternion.Euler(new Vector3(0f, 0f, angle)) * p2;
I am not exactly sure how I can just apply a rotation to all my point where`p1` should be pointing to the mouse position to ensure that the curve is properly align with my mouse.
Here a small screen shot of how it looks right now :
curve-pos.png
(2.2 kB)
Comment