Search code examples
c#unity-game-enginetransform

Unity3D face object where its moving


So I did a companion that flies with you and it is going fine with: this.transform.position = Vector3.Lerp(transform.position, player.transform.position + offset, speed * Time.deltaTime);

but now this is where it starts... currently I am using this but I want the object rotate itself where its moving: this.transform.LookAt(player, Vector3.up);

I would really appreciate a answer from you.

Have a great day.

TobiHudi


Solution

  • You can do this with some vector math. Store the previous location of your companion, then use the new target location to determine a direction vector. The code can look something like:

    private void Update()
    {
        // store our prev location
        Vector3 prevLocation = this.transform.position;
       
        // update the position as you are already doing
        this.transform.position = Vector3.Lerp(transform.position, player.transform.position + offset, speed * Time.deltaTime);
       
        // now calculate our direction using the targetLoc - prevLoc
        // assure to normalize so we have a non scaled vector, which is just a direction
        Vector3 newDir = (this.transform.position - prevLocation).normalized;
    
        // assign the rotation of our object to the direction we are now moving
        this.transform.rotation = Quaternion.LookRotation(newDir);
    }
    

    The above snippet is un-tested but is based around the Quaternion.LookRotation docs so it should work as intended.