Search Unity

Question transform.forward always returns (0,0) on x and y axis.

Discussion in 'Physics' started by ghegi, Jul 9, 2020.

  1. ghegi

    ghegi

    Joined:
    Jun 3, 2018
    Posts:
    28
    Code (CSharp):
    1. void FixedUpdate()
    2.     {
    3.  
    4.         if(Input.GetKeyDown(KeyCode.A))
    5.         {
    6.             if(isGrounded)
    7.             {
    8.                 rb.velocity = Vector2.up * jumpForce;
    9.             }
    10.         }
    11.  
    12.         if(Input.GetKey(KeyCode.S))
    13.         {
    14.             if(!isGrounded)
    15.             {
    16.                 Debug.Log(transform.forward.x + " " + transform.forward.y);
    17.                 rb.position = transform.forward * Time.deltaTime * boostForce;
    18.             }
    19.         }
    20.  
    21.     }
    It's a pretty simple code. If you're not on the ground and you press S, you should be boosting towards the direction the character is going to. But whenever I do this, it returns 0,0 and it makes my code not work obv which is frustrating me.
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    Attached is something that works. I say something because you don't talk about exactly how it should work. Here are some thoughts:

    Don't hard code KeyCode values into your script, use the input manager so that players can re-map them later.

    Check for key presses in Update (this is when Unity checks) not FixedUpdate.

    Use RigidBody.MovePosition to move a rigid body a fixed amount. (It will look much nicer if you apply a force).

    If you have not moved your object it will be facing (0,0,1) (remember y is up, x is right), so without rotation your code will return 0,0.
     

    Attached Files: