unity3d - Disabling diagonal movement in Unity 5 2D? (using C#) -


or rather should say, "effectively disabling diagonal movement".

there plenty of q/as online this, keep encountering same problem: when moving horizontally (left, example), can override current direction , start moving vertically (by pushing up), want. not work other way around! vertical movement can not override horizontal movement.

void update () {           float h = input.getaxis("horizontal");          float v = input.getaxis("vertical");           managemovement(h, v);  }      void managemovement(float horizontal,float vertical) {          if (vertical != 0f) {                 horizontal = 0f;                 vector3 movement = new vector3 (horizontal, vertical, 0);                 getcomponent<rigidbody2d> ().velocity = movement * speed;                 return;             }           if (horizontal != 0f) {             vertical = 0f;             vector3 movement = new vector3 (horizontal, vertical, 0);             getcomponent<rigidbody2d> ().velocity = movement * speed;             return;          } else {             vector3 nomovement = new vector3 (0, 0, 0);             getcomponent<rigidbody2d> ().velocity = nomovement;         }     } 

if reverse order of these if() statements, reverses problem. so, that's clue. i'm not great detective. love help!

try add else statement managemovement method:

void managemovement(float horizontal,float vertical) {      if (vertical != 0f) {             horizontal = 0f;             vector3 movement = new vector3 (horizontal, vertical, 0);             getcomponent<rigidbody2d> ().velocity = movement * speed;             return;         }       else if (horizontal != 0f) {         vertical = 0f;         vector3 movement = new vector3 (horizontal, vertical, 0);         getcomponent<rigidbody2d> ().velocity = movement * speed;         return;      } else {         vector3 nomovement = new vector3 (0, 0, 0);         getcomponent<rigidbody2d> ().velocity = nomovement;     } } 

Comments