Trigonometry issue

Hello,

I’m stuck with an issue for few days now and can’t manage to find the solution, could you guys help me ?

What I’m trying to do ?
So I’m trying to calculate a path from one point to another using trigonometry. Starting from point A, I want to go to point B, C, D or E.

``````float Movespeed = 1;
Vector3 CurrentPos = A.transform.position;
Vector3 FinalPos = B.transform.position;
float opp     ;
float hyppo   ;

float NewMoveX;
float NewMoveZ;

// calculating hyppothenuse, opposite and adjascent values
opp     = FinalPos.z - CurrentPos.z;

// calculating radian angle from A

// if opposite side is = 0, use arc-cosinus instead of arc-sinus for calculation
if (opp != 0f)
{
}
else
{
}

// Calculating 1 step in target direction
NewMoveX = Mathf.Cos (currRadian) * Movespeed;
NewMoveZ = Mathf.Sin (currRadian) * Movespeed;

Vector3 NewMoveVector = new Vector3(CurrentPos.x + NewMoveX, 0, CurrentPos.z + NewMoveZ);
``````

So as you can see in this drawing, this calculation is working properly only if the target point position.x is >= to the A position.x (case point B and point C are working properly, case point D and point F are not working properly).

In this image, you can see that if I use my calculation in this case, trying to go from A to F, my path will go in the good direction on Z axis, but in the opposite direction on X axis

Thanks for any help.

I suspect it’s because Arcsine and Arcosine only spit out values on half the unit circle. Arcsine is between -Pi/2 to Pi/2. Arcosine is always between 0 and Pi.

You can use a cross product to determine which side of the unit circle you are on, or in 2D just compare the X and Z values of your start and end positions.

If you can avoid all the trig, that’s even better though. Can you use Vector2.MoveTowards() instead?

Hi Garth, thanks for your response.

Vector3.MoveTowards() works perfectly. Thanks a lot.

just for my own knowledge, why should I avoid trig ?

Why go through the hassle if you don’t have to? Also - you can accomplish the same thing with vector math

``````Vector3 moveVector = (a - f).normalized * Movespeed;
``````