In my 2D game, I have two player-controlled game objects and I want to ensure that they always both have the same y-coordinate. For example, if one ran into a wall, I would want the other to stop as well. I’ve tried to implement this, seen in the code below, but it doesn’t look very good in game. I feel like this should be a super easy problem to solve, but I just can’t think of a solution. Does anyone have any suggestions as to the solution of my problem (in scripting or otherwise)?
void Update()
{
player1y = player1.transform.position.y;
player2y = player2.transform.position.y;
}
void FixedUpdate()
{
if (movement)
{
if (player1y >= player2y)
{
player1y = player2y;
player1.transform.position = new Vector3(player1.transform.position.x, player1y, player1.transform.position.z);
}
if (player2y >= player1y)
{
player2y = player1y;
player2.transform.position = new Vector3(player2.transform.position.x, player2y, player2.transform.position.z);
}
}