Search code examples
cameraunity-game-enginegame-physics

Using Main Camera with transform.LookAt at a target but no rotation of camera


I am writing an app in Unity3d which is a runner game .Now when I jump the character up(move it in y direction) then the camera rotates because I am using

transform.LookAt(character) 

1.the first image when the character is running properly

2.the second image is when the character jumps

image with normal motion image when the character jumps

I want the camera to lookAt the character without rotating


Solution

  • There are several solutions to this. Since you are manipulating directly the lookat direction through transform.LookAt(), you can simply change the target.

    LookAt method has an overload that let you specify the position of the target (Vector3 instead of Transform).

    You can than ignore the target's y coordinate and choose a fixed y value:

    Vector3 lookAtPosition = character.transform.position;
    lookAtPosition.y = fixedYPosition;
    transform.LookAt(lookAtPosition);
    

    Note that the solution above works only if the character stay always on the same plane (es. no more floor, stairs, etc..).