0
\$\begingroup\$

I have a camera follow script which is attached to the main camera and it follows the players position and rotation. The player needs to be near the top of the screen. However when I hit play, the player is shown at the center of the screen. This is how it looks in the scene view and this is how it should reflect when I hit play. Here the "y" position is -2 and "x" rotation is 0.

Screenshot1

But when I press play, the "y" position is still -2 but "x" rotation changes to -14.9. And the player is shown at the center of the screen and not near the top.

Screenshot2

Here is the camera follow script:

[SerializeField] Transform target;
public Vector3 defaultDist;
[SerializeField] float distDamp = .1f;    

public Vector3 velocity = Vector3.one;

Transform myT;

void Awake()
{
    myT = transform;
}

void LateUpdate()
{
    SmoothFollow();        
}

void SmoothFollow()
 {
    Vector3 toPos = target.position + (target.rotation * defaultDist);      

    Vector3 curPos = Vector3.SmoothDamp(myT.position, toPos,ref velocity ,distDamp);
    myT.position = curPos ;

    myT.LookAt(target, target.up);
 }
}

After I hit play, I want the x rotation to stay at 0 and the player to be shown near the top of the screen. Can someone please help?

\$\endgroup\$
3
  • \$\begingroup\$ Did you mean to override the camera's rotation with LookAt? \$\endgroup\$
    – DMGregory
    Jun 24, 2020 at 13:51
  • \$\begingroup\$ yes.....I would like to show the player near the top and without any rotation in the "x" position.. \$\endgroup\$ Jun 24, 2020 at 16:30
  • \$\begingroup\$ Then why are you using LookAt, which does not do those things? \$\endgroup\$
    – DMGregory
    Jun 24, 2020 at 16:40

1 Answer 1

0
\$\begingroup\$

myT.LookAt(target, target.up); tells the camera to look directly at the target.

A few options:

transform.LookAt(target, Vector3.up);
Vector3 rotation = transform.localEulerAngles;
rotation.x = 0; //remove x rotation
transform.localEulerAngles = rotation;

or

Vector3 lookTarget = target.position;
lookTarget.y = transform.y; //prevents x rotation
transform.LookAt(lookTarget);

or

//look at a position a fixed distance below the target
Vector3 offset = new Vector3(0, -2, 0);
transform.LookAt(target.position + offset);

As an aside, it is completely pointless to do myT = transform. You can just refer directly to the transform, which is also easier to read.

\$\endgroup\$
2
  • \$\begingroup\$ thanks for the code. This is now working as expected.... \$\endgroup\$ Jun 27, 2020 at 9:46
  • \$\begingroup\$ Awesome, glad to help! \$\endgroup\$
    – Kevin
    Jun 27, 2020 at 17:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .