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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ thanks for the code. This is now working as expected.... \$\endgroup\$ – single arrow games Jun 27 at 9:46
  • \$\begingroup\$ Awesome, glad to help! \$\endgroup\$ – Kevin Jun 27 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.