Rotate smoothly on sphere

Hi,
I try to rotate my player on the y-axis smoothly when I turn left(y=-45) or right(y=45) and it feels like I’ve tried all the examples but my player just starts spinning. I guess one of the problems is that my player is moving constantly on a globe (sphere) and the rotation is constantly changing?

The closest I got is this but when I turn left it rotates the wrong way:

    protected Vector3 leftRot = new Vector3(0, -45, 0);
    protected Vector3 rightRot = new Vector3(0, 45, 0);
    protected Vector3 normalRot= new Vector3(0, 0, 0);

  void Update()
    {
        currentRotation = RendererGO.transform.localEulerAngles;
        float LeftRight = 0;
        if (Input.touchCount > 0)
        {
            // touch x position is bigger than half of the screen, moving right
            if (Input.GetTouch(0).position.x > Screen.width / 2)
                LeftRight = 1;
            // touch x position is smaller than half of the screen, moving left
            else if (Input.GetTouch(0).position.x < Screen.width / 2)
                LeftRight = -1;
 }

        moveDir = new Vector3(LeftRight, 0, moveSpeed).normalized;
        //Rotations
        if (LeftRight == -1){
            this.transform.localEulerAngles = Vector3.Lerp(currentRotation, leftRot, Time.deltaTime * rotatesSpeed);
}
        else if (LeftRight == 1){
            this.transform.localEulerAngles = Vector3.Lerp(currentRotation, rightRot, Time.deltaTime * rotatesSpeed);
        }
        else{
            this.transform.localEulerAngles = Vector3.Lerp(currentRotation, normalRot, Time.deltaTime * rotatesSpeed);
        }
    }

I’ve tried som examples that shows Quaternion but I do not succeed… I would love to get some help with this one.

Can you please add the part where you are listening to user input and set the value for leftRot?

2 Answers

2

Thank you @taylank!

The following did the trick:

float angle = Mathf.LerpAngle(RendererGO.transform.localEulerAngles.y, maxAngle, Time.deltaTime * rotatesSpeed);
RendererGO.transform.localEulerAngles = new Vector3(0, angle, 0);

Thanks so much! That really helped. I really appreciate your answer.

When you’re dealing with rotation as vectors, lerp can be difficult to work with due to ambiguity in which direction to lerp in. For instance if you’re at angle 0 and you want to go 30, that’s fine, but if you want to go -30 instead that can be interpreted as 330 and a long lerp from 0 to 330 clockwise.

I’d recommend using Mathf.LerpAngle instead. There is a handy example you can use in the documentation.