Search Unity

Animations & GetKey?

Discussion in 'Scripting' started by spritesobhan, Apr 30, 2017.

  1. spritesobhan

    spritesobhan

    Joined:
    Mar 28, 2017
    Posts:
    73
    The animator and animation editor is really confusing so I'm trying to do this with scripting.

    This works pretty well except for when I'm holding L & J at the Same time...

    For example, if I have an animation for walking left, up, right, and down.
    How would I animate moving diagonally? Up and right at the same time? etc.

    (I'm using IJKL instead of WASD)

    Code (CSharp):
    1.  
    2.     void Update ()
    3.     {
    4.         if (Input.GetKeyDown (KeyCode.L) && !WalkRight.activeInHierarchy) {
    5.             WalkRight.SetActive (true);
    6.             GetComponent<SpriteRenderer> ().enabled = false;
    7.         }
    8.         if (Input.GetKeyUp (KeyCode.L) && WalkRight.activeInHierarchy) {
    9.             WalkRight.SetActive (false);
    10.             GetComponent<SpriteRenderer> ().enabled = true;
    11.         }
    12.         if (Input.GetKeyDown (KeyCode.J) && !WalkLeft.activeInHierarchy) {
    13.             WalkLeft.SetActive (true);
    14.             GetComponent<SpriteRenderer> ().enabled = false;
    15.         }
    16.         if (Input.GetKeyUp (KeyCode.J) && WalkLeft.activeInHierarchy) {
    17.             WalkLeft.SetActive (false);
    18.             GetComponent<SpriteRenderer> ().enabled = true;
    19.         }
     
  2. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    Do what other Game Developers have done in the past. decide on a priority and stick to it. Take virtually any 2.5 game as an example. you could make animations that shows the sprite moving in 8 directions, like Doom II. or in 4 directions like in Paper Mario. and in those examples when an actor is moving at an angle thats between two animations, they always make one of the animations a priority.

    and to handle conflicting controls. have the inputs add up a vector. if that vector is zero (which will happen for opposing inputs) then you don't update the animation, as if the player isn't pressing any buttons. so holding the "J" and the "K" keys will add up a (-1,-1) Vector2 so the character does a downleft animation (if thats inbetween 2 animations I would favor left). if the keys held down are "J","K", and "L" the vector adds up to (0,-1) since J and L cancel out and the character only moves down.