- Home /
Rotate Bezier Curve around object following mouse position
I am trying to rotate my object towards my mouse position on a radius position which has a Line renderer component as well as a custom bezier curve script that is getting 3 Vector3
points p0
, p1
, and p2
to trace the curve. (It also take a many vertexes to make the curve smoother).
Here 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());
}
}
I am feeding the 3 points from my player object using it's sprite radius as a base for the position :
public class PlayerManager : MonoBehaviour
{
public GameObject shield;
private SpriteRenderer sprite;
[SerializeField]
private float shieldDistance = 0f;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
BezierCurve curve = shield.GetComponent<BezierCurve>();
float x = sprite.bounds.extents.x + shieldDistance;
float y = sprite.bounds.extents.y + shieldDistance;
curve.p0 = new Vector3(0, y + 0.05f, 0f);
curve.p1 = new Vector3(x, y, 0f);
curve.p2 = new Vector3(x + 0.05f, 0, 0f);
}
}
This is what it gives me :
In the screenshot above, I would like the curve to rotate around the red circle following the mouse position.
I tried to rotate my player towards the mouse using the transform.lookAt
method but it doesn't rotate my curve along side with it (and I don't want the player to rotate really..) I also tried to apply a Quaternion.Eulers
on each of my point and the rotation seems to work but it just goes crazy and never stop rotating even when I am not moving the mouse :
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;
Is there any other way that I could apply a rotation on my 3 points following the mouse position and preferably to have the p1 to be the one that is pointing toward the mouse, so the curve is always "center" to the mouse.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Rotating Joystick on Touch 0 Answers
How to always rotate clockwise 1 Answer
Making a rotating object rotate with a parent object 1 Answer
Rotating a LineRenderer 0 Answers