finding an angle between two points (Joystick)
When I turn the joystick button in the opposite direction, I want to play animation according to the angle between the last point and the current point, the code works on the y-axis but does not give the correct result on the x-axis.
private Joystick joystick;
private bool isOverRange;
public Vector2 lastHandlePoint;
public Vector2 currentHandlePoint;
public float sensitive;
double angel;
public double currentAngle;
private void Start()
{
Initialize();
}
void Initialize()
{
joystick = FindObjectOfType<Joystick>();
}
private void Update()
{
CheckHandleState();
}
Vector2 HandleAbsoluteValue()
{
Vector2 handlePoint = InputJoystick();
Vector2 value = Vector2.zero;
float x = handlePoint.x;
float y = handlePoint.y;
// if (handlePoint.x > 0)
// {
// x = 1;
// }
// else
// {
// x = -1;
// }
//
// if (handlePoint.y > 0)
// {
// y = 1;
// }
// else
// {
// y = -1;
// }
return value = new Vector2(x, y);
}
Vector2 InputJoystick()
{
Vector2 value = Vector2.zero;
value = new Vector2(joystick.Horizontal, joystick.Vertical);
return value;
}
void CheckHandleState()
{
float handlePoint = InputJoystick().sqrMagnitude;
currentHandlePoint = HandleAbsoluteValue();
if (handlePoint > 0.8f)
{
lastHandlePoint = HandleAbsoluteValue();
isOverRange = true;
}
else
{
if (Input.GetMouseButton(0))
{
if (isOverRange && lastHandlePoint != currentHandlePoint)
{
isOverRange = false;
CalculateAngle();
}
}
}
}
void CalculateAngle()
{
float angle = Mathf.Atan2(currentHandlePoint.x - lastHandlePoint.x, currentHandlePoint.y - lastHandlePoint.y) *
180;
double degree = angle / Mathf.PI;
currentAngle = degree;
currentAngle = degree;
if (Math.Abs(degree) <= 180 + sensitive && Math.Abs(degree) >= 180 - sensitive)
{
print("turn");
}
}
twopoint-degre.png
(32.2 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613041417im_/https://answers.unity.com/themes/thub/images/avi.jpg)