- Home /
How to position the main camera in its script?
I have the following main camera script, which rotates as per the player's rotations, i.e. player and camera both move in the same direction at the same time. The script is working fine, however, I am unable to change the position of the main camera. It is literally on the ground and I want to make it higher. Here is the script:
public class FollowPlayer : MonoBehaviour
{
[SerializeField]
float mouseSensitivity;
public Vector3 cameraOffset;
public Transform Player;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
cameraOffset = transform.position - Player.transform.position;
}
void Update()
{
Rotate();
}
private void Rotate()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
Player.Rotate(Vector3.up, mouseX);
}
private void LateUpdate()
{
transform.position = Player.transform.position + (-Player.transform.forward * cameraOffset.magnitude);
transform.LookAt(Player.transform);
}
}
I want the current functionality to persist, but I just want to position the main camera according to my own offset values, but this script is changing those values at run time.
Answer by Tondoy · Mar 25 at 04:13 PM
Hi, to change the cameras position you could either create a additional variable containing the offset you want and add it to your current camera position:
private void LateUpdate()
{
Vector3 offset = new Vector3(0, 1.8f, 0);
transform.position = Player.transform.position + (-Player.transform.forward * cameraOffset.magnitude) + offset;
transform.LookAt(Player.transform);
}
Or create a offset Vector3 based on the start offset ignoring the players vertical view direction:
private void LateUpdate()
{
Vector3 offset = new Vector3(-Player.transform.forward.x * cameraOffset.magnitude, cameraOffset.y, -Player.transform.forward.z * cameraOffset.magnitude);
transform.position = Player.transform.position + offset;
transform.LookAt(Player.transform);
}
Your answer
Follow this Question
Related Questions
Help! I want to make a following camera but in with Y position is constant ? 2 Answers
Unity 2D Position Issues 0 Answers
Camera.main.position gives BCE0019 2 Answers
Is it possible to keep the player offset in place on the screen independent of resolution? 1 Answer
Offsetting local positions 2 Answers