[SOLVED] Gamepad's stick doesn't move object by round trajectory

The following code makes it move strange - it jerks by X and Y axes while I’m moving stick in a circle. Object should repeat circular motion of gamepad’s thumbstick. (XBox One Gamepad)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GamePadRenderer : MonoBehaviour {

    float speed = 10f;
    float xAngle;
    float yAngle;

    public GameObject leftStick;

    void Start () {

    }

    void Update () {
        xAngle = Input.GetAxis ("XAxis");
        yAngle = Input.GetAxis ("YAxis");

        if (Mathf.Abs(xAngle) >= 0.2f) {
            leftStick.transform.eulerAngles = new Vector3 (0, 0, -xAngle*speed);
        }
        if(Mathf.Abs(yAngle) >= 0.2f) {
            leftStick.transform.eulerAngles = new Vector3 (-yAngle*speed, 0, 0);
        }
    }
}

The problem is your code.

The way you set your eulerAngles, if there is any ‘y’ value greater than 0.2 in magnitude, you SET the eulerAngles. This overwrites what you did with the ‘x’ value.

Do something like this:

xAngle = Input.GetAxis("XAxis");
yAngle = Input.GetAxis("YAxis");
leftStick.transform.eulerAngles = new Vector3(-yAngle * speed, 0, -xAngle * speed);

If you prefer the 0.2 clamping of your x and y values, add that clamping before setting the eulerAngles:

xAngle = Input.GetAxis("XAxis");
yAngle = Input.GetAxis("YAxis");
if(Mathf.Abs(xAngle) < 0.2f) xAngle = 0f;
if(Mathf.Abs(yAngle) < 0.2f) yAngle = 0f;
leftStick.transform.eulerAngles = new Vector3(-yAngle * speed, 0, -xAngle * speed);

If you prefer the overlapping logic of your original code, so that it conserves changes done previously in your code, you do this:

xAngle = Input.GetAxis ("XAxis");
yAngle = Input.GetAxis ("YAxis");

if (Mathf.Abs(xAngle) >= 0.2f) {
    var e = leftStick.transform.eulerAngles;
    e.z = -xAngle * speed;
    leftStick.transform.eulerAngles = e;
}
if(Mathf.Abs(yAngle) >= 0.2f) {
    var e = leftStick.transform.eulerAngles;
    e.x = -yAngle * speed;
    leftStick.transform.eulerAngles = e;
}

note how here we conserve the changes made in the previous x statement.

Of course, this logic means that if you release the stick abruptly, your code logic will maintain the ‘leftStick’ extended even though you no longer are, because you only update if it’s larger than 0.2. But if that’s what you want, this is how you get that.

1 Like

That was stupid mistake :p. Such broad answer, thanks a lot.