Hello,
I’m trying to create a script to allow a camera to follow a ball and rotate around it using J and L (for now). I’m currently having issues getting the camera to look at the ball while rotating, I’m using transform.LookAt(player.transform.position);
but my other line transform.position = player.transform.position + offset;
is overriding it and not allowing it to rotate.
as of yet I have no idea how to go about fixing this issue.
Thank you for taking the time to look at my question!
Here’s The entire Script just in case;
public class CameraController : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
public int rotateSpeed;
// Use this for initialization
void Start ()
{
offset = transform.position;
}
// Update is called once per frame
void LateUpdate ()
{
transform.LookAt(player.transform.position);
transform.position = player.transform.position + offset;
//Controls
if(Input.GetKey(KeyCode.J))
{
transform.RotateAround(player.transform.position - offset, Vector3.down, Time.deltaTime * rotateSpeed);
}
else if(Input.GetKey(KeyCode.L))
{
transform.RotateAround(player.transform.position - offset, Vector3.up, Time.deltaTime * rotateSpeed);
}
}
}
There are several ways to approach this problem. Working within the framework of your existing code, there are a few changes that make it behave how you describe:
public class CameraController : MonoBehaviour
{
public Transform player;
private Vector3 offset;
public int rotateSpeed;
void Start ()
{
offset = transform.position - player.position;
}
void LateUpdate ()
{
if(Input.GetKey(KeyCode.J))
{
transform.RotateAround(player.transform.position, Vector3.down, Time.deltaTime * rotateSpeed);
offset = transform.position - player.position;
}
else if(Input.GetKey(KeyCode.L))
{
transform.RotateAround(player.transform.position, Vector3.up, Time.deltaTime * rotateSpeed);
offset = transform.position - player.position;
}
transform.position = player.transform.position + offset;
transform.LookAt(player.transform.position);
}
}
I tried plugging in your code but the camera just ended up in a static position staring at the ball from a distance. No idea why. A buddy of mine suggested this code but the offset aspect of it doesn’t work as well as one would hope.
public class CameraController : MonoBehaviour
{
public Transform player;
private Vector3 offset;
public float rotateSpeed;
public bool isRotate = false;
void Start ()
{
offset = transform.position;
}
void LateUpdate ()
{
transform.position = player.transform.position + offset;
transform.LookAt(player.transform.position);
if(isRotate)
{
//Controls
if(Input.GetKey(KeyCode.J))
{
offset = Quaternion.AngleAxis(player.transform.position.x * rotateSpeed, Vector3.down) * offset;
}
else if(Input.GetKey(KeyCode.L))
{
offset = Quaternion.AngleAxis(player.transform.position.x * rotateSpeed, Vector3.up) * offset;
}
}
}
}