Search Unity

Movement on top down is all skew wiff

Discussion in '2D' started by ABeardedWonder, Oct 23, 2016.

  1. ABeardedWonder

    ABeardedWonder

    Joined:
    Oct 4, 2016
    Posts:
    8
    Code (CSharp):
    1.     void FixedUpdate()
    2.     {
    3.      
    4.  
    5.         float moveHorizontal = Input.GetAxis ("Horizontal");
    6.  
    7.         rb2d.velocity = new Vector2 (moveHorizontal * maxSpeed, rb2d.velocity.y);
    8.  
    9.  
    10.  
    11.         float moveVertical = Input.GetAxis ("Vertical");
    12.  
    13.         rb2d.velocity = new Vector2 (moveVertical * maxSpeed, rb2d.velocity.x);
    14.      
    15.  
    16.  
    17.     }
    18. }
    19.  

    Im sure i'm just doing it wrong, but its the first time Ive tried to make movement from notes i made watching tutorials and not following a tutorial step by step.

    Basically the issue im having is

    Up key moves me Left
    Down key moves me Right
    Left key moves me Down
    Right key moves me Up


    No idea where ive gone wrong. I tried moving X and Y around after rb2d.velocity but then it just moved me diagonally with the Up and Down key, and Left and Right did nothing at all



    UPDATE:

    Stepdad sugested moving the top and bottom code around and it worked but i have no idea why?

    anyone able to explain?
     
    Last edited: Oct 23, 2016
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,501
    First, you can get both axes at the same time as a Vector2. That would be your input values.
    Second, don't modify the velocity of a rigidbody directly unless you have very good reasons. Otherwise you should be using something like rb.MovePosition().
    Third, you have to transform the inputs based on the camera view direction. Unless you're doing it in 2d? Maybe not necessary then.

    Anyway, here's some psuedo code. Do not assume this is a literal fix.
    Code (csharp):
    1.  
    2.             float speed = 0.1f;
    3.             Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    4.             _rb.MovePosition(Camera.main.transform.InverseTransformDirection(input) * speed);
     
  3. lollypap54

    lollypap54

    Joined:
    Oct 19, 2016
    Posts:
    8