Determining the rotation of an object based on its upcoming position?

Hi,

I have an object that I would like to rotate so that it’s “head” (one end of the rectangle. I want to be able to apply this to any object though) is facing the direction that it is moving in. I don’t have a target that I want to look at so the object needs to be able to know it’s correct rotation based on it’s upcoming movements. See the following picture for an example :

My idea was to find the inverse of tan of the opposite and adjacent values ( ie x and y ) and then to convert those radians to the new rotation angle. However, this doesn’t seem to give me the desired result?

Here is the code that I’m using:

        float z = Mathf.Rad2Deg * Mathf.Atan(x / y);

        GetComponent<Rigidbody>().rotation = Quaternion.Euler(0,0, z);

My object is moving in small increments vertically and horizontally based on the 2D plane every frame so I was thinking of doing something like so to make it seem like a more realistic rotation but it’s also not giving me the result that I’m looking for. What would you recommend?

     float inc = Mathf.Rad2Deg * Mathf.Atan(x / y);

        if(inc > 0) { 
        for(int i = 0; i < inc; i++) {
            z = i;
            GetComponent<Rigidbody>().rotation = Quaternion.Euler(0,0, z);
        }
        }
        else
        {
            for (int i = 0; i > inc; i--) {
            z = i;
            GetComponent<Rigidbody>().rotation = Quaternion.Euler(0,0, z);
        }

What do you mean by "I want to get the angle of the rotation around an object's local X and Y axis." local axis also rotates with gameobject. You can't get a relative rotation in its local axis. Did i get wrong ?

1 Answer

1

Something along the lines of setting the rotation euler angles to the rigidbody’s velocity vector, can’t remember. Good thing I can point you to a script that does exactly that!

It does have damping, but the whole principle is in there.

I don't have a target that I want to look at so the object needs to be able to know it's correct rotation based on it's upcoming movements. That code seems to require a target?

I thought since I can rotate around those axises they also have a time when the rotation around it is zero, and maybe I can get the amount of rotation that has been done around it. I've read a post on stackoverflow about how to get an angle around custom axis using projection, but it didnt work well for me. Well if this is really impossible, or more like doesnt make sense, I'll just stop trying to make this work (cuz it wont)