0
votes

I'm making a script which should rotate a GameObject like a joystick, which means that only X and Z axes must change. So i'm using sin and cos functions to calculate rotation angles. But for some reason Y axis changes as well.

public float alpha;

void Update () {
        alpha += Time.deltaTime;

        var x = R * Mathf.Cos(alpha);
        var z = R * Mathf.Sin(alpha);
        transform.Rotate(new Vector3(x, 0, z) * Time.deltaTime);
    }

So the question is how do I stop Y axis from changing or maybe there is another way to rotate the object like a joystick.

P.S. I am using Unity 2017.4.13f1

2
I am not a Unity-user, but I do not fully understand your code. What is R (radius? rotation matrix?) Why do you multiply your rotation vector with your deltatime, and not with your target angle? - Lemonbonbon
deltaTime is used to increase the angle very smoothly and R is a multiplier to increase the angle of rotation. It's just a floating point number. - kastowan

2 Answers

0
votes

In your update function you may write :

public float alpha;
public Vector3 rotation;
void Start(){
    rotation = transform.rotation.eulerAngles;
}

void Update () {
    alpha += Time.deltaTime;
    var x = Mathf.Cos(alpha);
    var z = Mathf.Sin(alpha);
    rotation.x = x;
    rotation.z = z;
    transform.rotation = Quaternion.Euler(rotation*time.deltaTime);
}

I couldn't understand the R variable that you multiplied with Sin and Cos. where is that R defined???

0
votes

I decided to set Y axis to 0 every frame. Maybe not the most elegant solution but it works just as I needed.

Vector3 rotationVector;

void Start()
{
    rotationVector = new Vector3();
}

private float alpha;
public float multiplier;

void Update () 
{
    alpha += Time.deltaTime;

    rotationVector.x = Mathf.Cos(alpha);
    rotationVector.z = Mathf.Sin(alpha);

    transform.Rotate(multiplier * rotationVector * Time.deltaTime);
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, transform.eulerAngles.z);
}