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

Bug Issue with moving player in 3D.

Discussion in 'Physics' started by sunsetworld, Jun 21, 2023.

  1. sunsetworld

    sunsetworld

    Joined:
    Jul 21, 2020
    Posts:
    23
    Hello!

    I'm making a 2.5D jam game with a few other people. I'm working on the mechanic where the player can toggle between a position slightly back on the Z and then to their original position. However, it doesn't work sometimes.

    Enclosed is the code and a video demonstration.

    Thanks.

    Sam.



    Code (CSharp):
    1. private bool _layer0 = true;
    2. [SerializeField] private float layer1Z;
    3. private bool _canSwitchLayer = true;
    4.  
    5. void SwitchLayer()
    6.     {
    7.         if (Input.GetKeyDown(KeyCode.Mouse0) && _canSwitchLayer)
    8.         {
    9.             _canSwitchLayer = false;
    10.             Vector3 newPlayerLayer = transform.position;
    11.             if (_layer0)
    12.             {
    13.                 _layer0 = false;
    14.                 newPlayerLayer.z = layer1Z;
    15.  
    16.             }
    17.             else if (!_layer0)
    18.             {
    19.                 _layer0 = true;
    20.                 newPlayerLayer.z = 0;
    21.             }
    22.             transform.position = newPlayerLayer;
    23.  
    24.             _canSwitchLayer = true;
    25.         }
    26.     }
     
  2. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,630
    How/where is SwitchLayer() being called?

    Also, what's the purpose of _canSwitchLayer? it's set to false and then just back to true every time the player clicks the mouse.
     
  3. sunsetworld

    sunsetworld

    Joined:
    Jul 21, 2020
    Posts:
    23
    SwitchLayer() is being called in Update.

    I threw in _canSwitchLayer() hoping that it would fix the problem, but it doesn’t.
     
  4. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,630
    The
    I'd guess the issue is unrelated to this script then. Hard to tell what the cause might be without taking a look at the rest of your code.
     
  5. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    Your issue is outside this function. The function is not very clear in it's logic, though. Your _canSwitchLayer assignments serve no purpose. Also your naming is confusing: you are using the name "layer" in two variables, the other one is Vector3, the other one is float. I would use bool, enum or int for layer, depending on if you have 2 or more layers.