- Home /
The question is answered, right answer was accepted
Position camera between two players
I'm trying to figure out how to calculate the offset position of the camera to follow both players based on the midpoint and determine the new camera position. I have most of it figured out, can anyone take a look and point me in the right direction?
Here's what I have so far:
{ public GameObject player1; public GameObject player2;
private Vector3 offset;
private Vector3 midPosition;
// Start is called before the first frame update
void Start()
{
midPosition = (player1.transform.position + player2.transform.position) / 2.0f;
// Need to calculate offset based on midpoint
offset = transform.position - player1.transform.position;
}
// Update is called once per frame
void Update()
{
midPosition = (player1.transform.position + player2.transform.position) / 2.0f;
// Need to calculate new camera position based on midpoint
transform.position = offset + player1.transform.position;
}
}
It looks like it's all there - the last line just needs to use the calculated midPosition: transform.position = offset + midPosition;
Answer by GameBrews · Sep 08, 2021 at 06:09 PM
As suggested by @Cherie , it does seem to be in order except the last line. You set the new position without using the calculated midPosition.
change:
transform.position = offset + player1.transform.position;
to:
transform.position = offset + midPosition
And about the offset: It is calculated once inside Start()
, before you reposition the camera between the players, so the initial offset between where you placed player1 and the camera in the scene editor will be used when the scene is running.
You can address this by calculating the midpoint once inside Start()
, as you already have, set the camera position to it and only than calculate the offset.,As suggested by @Cherie , it does seem to be in order except the last line. You set the new position without using the calculated midPosition.
change:
transform.position = offset + player1.transform.position;
to:
transform.position = offset + midPosition
And about the offset: It is calculated once inside Start()
, before you reposition the camera between the players, so the initial offset between where you placed player1 and the camera in the scene editor will be used when the scene is running.
You can address this by calculating the midpoint once inside Start()
, as you already have, set the camera position to it and only than calculate the offset.