Vector3.RotateTowards not working on certain vectors

I’m currently trying to make the elbow of my character rotate towards a point found from a raycast, but it starts glitching out when I change the vector I want to rotate.

It works fine for transform.forward & -transform.forward (just that it doesn’t point in the direction I want), but if the vector is set to transform.right or -transform.right, the part starts glitching out and never fully looking at the point.

Here is my code below:

public Transform rayOrigin; //the ray origin
public float rayLength;     //ray length
public float speed;         //rotate speed

void Update()
{
    float step = speed*Time.deltaTime;
    if(Physics.Raycast(rayOrigin.position, rayOrigin.forward, out RaycastHit raycastHit, rayLength))
    {
        Vector3 targetDir = raycastHit.point - transform.position;
        Vector3 rot = Vector3.RotateTowards(-transform.right,targetDir,step,1f);
        transform.rotation = Quaternion.LookRotation(rot);  
    } 
}

Yes, the vector I’m trying to rotate is a child of multiple objects if you think that has something to do with it.

Thanks in advance :slight_smile:

I’m not sure you understand what you are doing here and I don’t get why you would put transform.right as the “from” direction. RotateTowards does not “rotate” the first vector somehow. It just outputs a direction vector that is in between the from direction and the to direction by a certain amount. LookRotation on the other hand creates an actual rotation so that the forward axis points along the given direction vector.

So it seems you have a logic error here. What exactly do you want to achieve? As I said, the first argument of LookRotation is only concerned about aligning the forward axis with the given direction. The second argument is just use as a “hint” to get the local z orientation around the forward axis the way you want. When you don’t supply that second argument it defaults to Vector3.up. so the rotation that is created will have it’s up direction best aligned with the world up direction (or up of the coordinate space you’re working with when it’s not world space).

Are you trying to align the object’s right (or left) axis with the target axis? That is possible with RotateTowards and LookRotation but requires a bit more work.

A solution can be found here.

Though the easiest solution is to wrap your object in an empty gameobject, align the actual object in that empty object so that your desired axis aligns with the empty object’s forward axis and then you can use LookRotation as usual and align the forward axis and it should look right.