How can i prevent my character rotating around nonY axes?

So i’m working on a game with third person shooter type controls. It has mouselook, wasd keys move based on camera pointing. But since the character is on the ground, they can only move on the XZ plane, and only rotate around the Y axis. In theory anyway

I wrote some code for slow turning, it gradually rotates the target towards the direction they’re moving. (not necessarily the direction the camera is facing, but often)
It mostly works to limiit the character’s rotation, but sometimes, for very large rotations (like if i try to move in the opposite direction the character is facing) it screws up, and in order to point at the target, my character gets flipped through several other axes to find a shorter path than spinning around Y.

I wrote most of my code, but the solution for finding the direction of rotation, i may have found on a random unity answers post. And therefore don’t fully understand it.

It’s worth noting, the character is using a characterController. Though i’m not sure it has any special functions for this. Most notably though, there is no rigidbody, and so i can’t just freeze rotation on the undesired axes

The relevant part of my code:

//Code for rotating towards direction
        Quaternion newTargetRot = (Quaternion.FromToRotation(transform.forward, VectorTools.Flatten(controller.velocity)) * body.transform.rotation);
        if (newTargetRot != targetTurningRotation)
        {
            Shortcuts.ClearConsole();
            targetTurningRotation = newTargetRot;

            Vector3 fwdCurrent = body.transform.rotation * Vector3.forward;
            Vector3 fwdTarget = targetTurningRotation * Vector3.forward;

            float angleCurrent = Mathf.Atan2(fwdCurrent.x, fwdCurrent.z) * Mathf.Rad2Deg;
            float angleTarget = Mathf.Atan2(fwdTarget.x, fwdTarget.z) * Mathf.Rad2Deg;

            float diff = Mathf.DeltaAngle(angleCurrent, angleTarget);

            if (diff < 0f)
            {
                targetTurningDirection = -1;
            }
            else
            {
                targetTurningDirection = 1;
            }
            Debug.Log("Calculating! "+targetTurningDirection);
            turningAngleToTarget = Mathf.Abs(diff);
        }
        else
        {
            turningAngleToTarget = Quaternion.Angle(targetTurningRotation, body.transform.rotation);
        }

        if (turningAngleToTarget < angularSpeedPerFixedUpdate)
        {
            body.transform.rotation = targetTurningRotation;
            anim.SetFloat("Direction", 0f);
        }
        else
        {
            float fraction = angularSpeedPerFixedUpdate / turningAngleToTarget;
            Debug.Log("Turning: " + fraction);
            anim.SetFloat("Direction", (turningAngleToTarget / 180f));
            body.transform.rotation = Quaternion.Lerp(body.transform.rotation, targetTurningRotation, fraction);
        }

I think the main problem here is that Quaternion.Lerp is too good at finding the shortest path, and that path is often not only around my desired axes. So i probably need to replace the lerp with some custom lerping. but how?

What can i do to fix this?

poke

alternative lerping solution, anyone?

You are probably right that Quaternion.Lerp is giving values off your desired axis. And, it’s a little hard to dig through the code you provided, unless you can provide the whole script and it’s dependencies or a simplified version showing the problem, which I know isn’t always possible.

So what I will do is provide a small script that I frequently use when I want an object to face the direction of it’s movement:

using UnityEngine;
using System.Collections;

public class FaceMovement : MonoBehaviour
{
    public float turnSpeed = 360f; // degrees/second

    private Vector3 _lastPos;

    void Start()
    {
        _lastPos = transform.position;         
    }
     
    void Update()
    {
        Vector3 lookAtDir = transform.position - _lastPos;
        transform.forward = Vector3.RotateTowards(transform.forward, lookAtDir, (turnSpeed * Mathf.Deg2Rad * Time.deltaTime), 0f);
        _lastPos = transform.position;
    }
}

The code controlling the movement of the object can be in an entirely different script, this script just rotates the object to face the direction it is moving. So as long as the code controlling the object keeps it on a level plane (xz), then this should keep the object rotating around the y axis. If you want to integrate it into your current script, it looks like the values you want to put into Vector3.RotateTowards() is your forward, and velocity vectors (the ones in the first line of the code you provided).

Hopefully this will help you!

hi @jmjd , thanks for your answer

I may be wrong here, but i don’t think my whole code is relevant, since i’m 99% sure the problem is just Quaternion.Lerp interpolating smoothly over the surface of a 4D sphere, as quaternions do. They lerp well.

The problem is, when i start moving in the exact opposite direction, then all possible rotations are equidistant to the target point.

i’m not quite clear on how your solution will prevent this though. I don’t see anything in Vector3.RotateTowards that will restrict it to rotating around a single axis. Can you elaborate on it?

So for me, the quickest way to solve a coding problem is to be able to reproduce it. You’re probably right, and the rest of your code has nothing to do with causing your problem… but it is relevant to solving it. I understand that it’s not always possible to provide more code, but if I can’t actually run your code and figure out what it’s doing, then I can only read your code and give suggestions to what might help, instead of actual solutions. So if you can provide more… enough so that someone can reproduce the problem on their end, then yes it will be very helpful.

Anyways, there’s nothing explicit in my code that is restricting it to only rotate around the y-axis. But did you try it? Place that script on an object and move it around on a flat plane. Is it doing what you wanted it to do, face the direction of movement? (You can just throw it on a cube in an empty scene, and move it in the editor in play mode. Move it straight forward, then straight back.)

Now, the code I gave you is a general facing direction of movement script, and I said that as long as the objects movement stayed on a flat plane, then it would only rotate around the y-axis. We obviously don’t have the code for Vector3.RotateTowards(), but I’ve used it countless times for the behavior that you are describing.

My guess to how it works though is that it finds an orthogonal vector to the two that you provide, and then rotates the ‘from’ vector towards the ‘to’ vector using the orthogonal one as the rotation axis. So if you provide two vectors on the x-z plane, then it will only rotate around the y axis.

If your character’s movement does include some y movement due to slopes or jumping, then we can just make that explicit by zeroing out the y values to the vectors we pass in.

Here’s an updated script that hopefully makes it clearer:

using UnityEngine;

public class FaceMovement : MonoBehaviour
{
    public float turnSpeed = 360f; // degrees/second

    private Vector3 _lastPos;

    void Start()
    {
        _lastPos = transform.position;
    }

    void Update()
    {
        Vector3 from = transform.forward;
        from.y = 0f;
        Vector3 to = transform.position - _lastPos;
        to.y = 0f;

        transform.forward = Vector3.RotateTowards(from, to, (turnSpeed * Mathf.Deg2Rad * Time.deltaTime), 0f);
        _lastPos = transform.position;
    }
}

Hope this helps, and let me know if you have anymore questions about how it’s working.

1 Like

i finally got around to testing this. it works like a dream, amazing, and it’s massively reduced the size of my turning code down to 3 lines.

I had no idea you could assign a value to transform.forward, i thought that was a read only property. that’s crazy

Great! I’m glad that worked out for you!

1 Like