2
votes

Trying to implement method to rotate object in unity based on Vertical and Horizontal Axis which gets determined by position of cursor on an image.

Creating a 3D game for mobile with joystick for controls. The aim is to rotate using the joystick. Example of image: https://imgur.com/a/hd9QiVe The green circle moves with users press and returns X and Y values between -1 to 1 with 0 being in middle. Just to visualise how input happens: https://imgur.com/a/8QVRrIh As shown in image I simply want angle or a way to move object in direction that user input is detected.

Tried several methods for calculating angle by using atan and tan but my maths is quite bad and Im not entirely sure I grab correct values in first place.

//background joystick refers to white circle in first image

        pos.x = (pos.x / backgroundJoystick.rectTransform.sizeDelta.x);
        pos.y = (pos.y / backgroundJoystick.rectTransform.sizeDelta.y);
        inputVector = new Vector3(pos.x * 2f, 0, pos.y * 2f);
        inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

//grabbing axis input

public float Horizontal()
{
    if (inputVector.x != 0)
    {
        return inputVector.x;
    }
    else
        return Input.GetAxis("Horizontal");
}

public float Vertical()
{
    if (inputVector.z != 0)
    {
        return inputVector.z;
    }
    else
        return Input.GetAxis("Vertical");
}

As shown in code angle is necessary from input.getaxis for vertical and horizontal to direct object towards the angle. Currently the formulas used do not provide any angles.

1

1 Answers

1
votes

If you want to get the angle of a Vector, use the Vector2.SignedAngle():

var inputAngle = Vector2.SignedAngle(Vector2.right, inputVector);

Angles are relative, which is why you need to specify Vector2.right as the first parameter. There's also a Vector2.Angle() method, but that just returns the distance between two angles, and doesn't take into account the direction.

If you need to verify that your input vectors are what you think they are, use Debug.Log() to print your inputVector.