How can i set the camera to be automatic behind the player ?
I have a script attached to a camera and the camera follow the player.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
public GameObject objectToFollow; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - objectToFollow.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
transform.position = objectToFollow.transform.position + offset;
transform.LookAt(objectToFollow.transform);
}
}
Now instead changing the camera position in the scene view to be behind the player i want to use a bool variable to do it automatic.
So i changed the script to this:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
public GameObject objectToFollow; //Public variable to store a reference to the player game object
public bool behindPlayer = false;
private Vector3 cameraStartPos;
// Use this for initialization
void Start()
{
cameraStartPos = transform.position;
// Put the camera behind the player
if (behindPlayer == true)
{
transform.position = (objectToFollow.transform.position - (objectToFollow.transform.forward * 5) + (objectToFollow.transform.up * 2));
}
}
private void Update()
{
if (behindPlayer == true)
{
transform.position = (objectToFollow.transform.position - (objectToFollow.transform.forward * 5) + (objectToFollow.transform.up * 2));
}
else
{
transform.position = cameraStartPos;
}
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
transform.position = objectToFollow.transform.position;
transform.LookAt(objectToFollow.transform);
}
}
But now i'm not using the offset if it's needed. The line: transform.position = objectToFollow.transform.position; prevent from the variable bool behindPlayer to work. Without this line the camera will follow the player but not like in the script above.
All i want is to add to the first script version a bool variable so i can change the camera position without changing the following script idea.
Your answer
Follow this Question
Related Questions
Menu object not responding 0 Answers
How can i move object between two positions ? 1 Answer
Update() and FixedUpdate() not running on C# scripts 0 Answers
Scripting Help desperately needed. 1 Answer