Search Unity

Triggering animation in NPC when Player presses Left/right Arrow keys or A or D key.

Discussion in 'Scripting' started by cristo, Apr 28, 2017.

  1. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Hi, I'm trying to make it so that when the player is within a certain of a non player character, and the player is pressing the LeftArrowKey, the RightArrowKey or A or D (in the WASD), an animation plays on the NPC.
    I understood that "Horizontal" covered these buttons like Fire1 covers the LeftMouseButton.

    If anyone would please point me to a solution that would be great.


    Code (CSharp):
    1. // Update is called once per frame
    2.     void Update () {
    3.  
    4.         bool down = Input.GetButtonDown("Horizontal");
    5.         bool held = Input.GetButton("Horizontal");
    6.         bool up = Input.GetButtonUp("Horizonal");
    7.        
    8.         if (Vector3.Distance(Player.transform.position, NPC.transform.position) < Distance && Input.GetButtonDown("Horizontal")) {
    9.             NPC.GetComponent<Animation>().Play("Animation_One");
    10.         }
    11.     }
    12.  
    13.  
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    "Horizontal" is the name of an axis, not the buttons; it works with GetAxis.
    Code (csharp):
    1. if (Vector3.Distance(etc) < Distance && Input.GetAxis("Horizontal") != 0f)
    Be advised that this is one of very rare instances where it's okay to check for exact equality (== and != ) with floats, because 0 is the exact value that's returned when the axis isn't being pressed. Analog input or joysticks might make that dicey, though, if you allow non-keyboard input, so you'd want to check for a range instead if so.
     
    cristo likes this.
  3. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Thanks for your feedback.