help!, mathf.atan2 return same value over and over again

im making match3 game and use mathf.atan2 to caculate angle when player swipe on screen but it just return same value over and over again no matter wiich direction i swipe, i dont know why?


private void OnMouseDown()
{
firstTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}

private void OnMouseUp()
{
    finalTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    CaculateAngle();
}

void CaculateAngle()
{
    swipeAngle = Mathf.Atan2(finalTouchPosition.y - firstTouchPosition.y, firstTouchPosition.x - firstTouchPosition.x) /** 180/Mathf.PI*/;
    Debug.Log(swipeAngle);
}![126753-bandicam-2018-10-27-18-35-49-626.jpg|862x254](upload://mWx17IxeuKoHGJe6fjWtjC9NgPR.jpeg)

Carefully read this: Mathf.Atan2(finalTouchPosition.y - firstTouchPosition.y, firstTouchPosition.x - firstTouchPosition.x)

1 Answer

1

First, without any data on what finalTouchPosition and firstTouchPosition are feeding into Atan2, we can only guess from way out here as to those input values. What I see in the debug log are a series of entries that are recognizable as 90 degree angles, some positive and some negative, indicating that swipes may be returning very similar values in x but very different values in y, resulting in those angles (correctly).


That said, your code’s “x” coordinate reads (pasted from copy)

firstTouchPosition.x - firstTouchPosition.x

Which means your ‘X’ coordinate will always be zero, and that’s why you’re only getting 90 degree angles.


I should detail that Atan2 is “oriented” according to the standards of math, where the return value is in Radians (not degrees - convert with Mathf.Rad2Deg), where “zero” degrees is X positive (3 o’clock), and positive rotations are counterclockwise. Students frustrate over this in high school math classes everywhere, assuming that the trig functions should work “like a clock face”, but they never have.


So, start by correcting the “x” value subtraction, convert to degrees if that’s what you’re expecting to use, and adjust the output to comport with your expectation of where “zero” degrees should be, and the direction of the rotation you prefer.

thank you, it is really helpful !, i retype : finalPosition.x - firstTouchPosition.x and it works