0
\$\begingroup\$

I have a LineRenderer that draws a line between two points, Vector3 startPos and Vector3 endPos. How can I get the angle between these points, and apply it to an objects transform rotation, so that it points in that direction?

Here is my code that draws a line between 2 points by dragging your mouse, if you want to test just Replace the Interact methods with Input.MouseButtonDown(1), hold and up.

Vector3 startPos;
Vector3 endPos;
float angle;

LineRenderer lr;

private void Awake()
{
    lr = GetComponent<LineRenderer>();
    lr.useWorldSpace = true;
}

public override void InteractOnDown()
{
    base.InteractOnDown();

    lr.enabled = true;
    lr.positionCount = 2;
    startPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(0, startPos);
}

public override void InteractOnHold()
{
    base.InteractOnHold();

    endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point;
    lr.SetPosition(1, endPos);
}

public override void InteractOnUp()
{
    base.InteractOnUp();

    lr.positionCount = 0;
    lr.enabled = false;
}
\$\endgroup\$
2
\$\begingroup\$

You should always question whether an angle is actually necessary, or if a vector would suffice.

Here, all we need is the vector from the start to the end:

Vector3 direction = endPos - startPos;

Then you can use that vector to align the forward vector of your transform:

transform.forward = direction;

Or you can compute a new orientation with transform.rotation= Quaternion.LookRotation(direction, localUp) if you want more control over the object's twist around this direction axis.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.