Search Unity

Switching to negative input direction with OnTriggerEnter

Discussion in 'Scripting' started by poolofclay33, Oct 19, 2018.

  1. poolofclay33

    poolofclay33

    Joined:
    Oct 4, 2016
    Posts:
    51
    I'm having issues with my player switching movement direction when they start running backwards. My thought was to have a collider, where if the player hits the collider, then the camera will switch direction to be facing the back of the player and the player's input directions will become negative which will inverse their controls so the player will technically be moving forwards after this transition.

    Here's what I have for code so far to better illustrate my issue:
    Code (CSharp):
    1.     public void OnTriggerEnter(Collider other)
    2.     {
    3.         if (other.tag == "CamBlock")
    4.         {
    5.             _camAnim.Play("Swap");
    6.             _inputs.x = -Input.GetAxis("Horizontal");
    7.             _inputs.z = -Input.GetAxis("Vertical");
    8.         }
    9.     }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    That would only work for one frame on the input. You have to add a variable in update like
    Code (csharp):
    1.  
    2. int direction = 1;
    3.  
    4. void Update(){
    5. inputs.x = Input.GetAxis("Horizontal") * direction;
    6. }
    7.  public void OnTriggerEnter(Collider other)
    8. {
    9.   direction = -1;
    10. }
    11.  
     
  3. poolofclay33

    poolofclay33

    Joined:
    Oct 4, 2016
    Posts:
    51
    Thank you so much! That worked great! It's always a simple solution like that too :D