Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Restricting y-axis Player Movement

Discussion in 'Scripting' started by DivineMango, Nov 25, 2014.

  1. DivineMango

    DivineMango

    Joined:
    Nov 5, 2014
    Posts:
    4
    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)?

    Code (CSharp):
    1. void Update()
    2.     {
    3.         player1y = player1.transform.position.y;
    4.         player2y = player2.transform.position.y;
    5.     }
    6.  
    7.     void FixedUpdate()
    8.     {
    9.         if (movement)
    10.         {
    11.             if (player1y >= player2y)
    12.             {
    13.                 player1y = player2y;
    14.                 player1.transform.position = new Vector3(player1.transform.position.x, player1y, player1.transform.position.z);
    15.             }
    16.  
    17.      
    18.             if (player2y >= player1y)
    19.             {
    20.                 player2y = player1y;
    21.                 player2.transform.position = new Vector3(player2.transform.position.x, player2y, player2.transform.position.z);
    22.             }      
    23.         }
     
  2. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,680
    What is the issue exactly?
     
  3. DivineMango

    DivineMango

    Joined:
    Nov 5, 2014
    Posts:
    4
    The player movement is restricted, except when one of them hits a wall, the other stutters up and down instead of completely stopping.
     
  4. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,680
    So what happens when a player hits the wall, in code,? Movement = false?