Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Add rigidbody2d.velocity according to axis arrows

Discussion in 'Physics' started by bora155, Jul 29, 2021.

  1. bora155

    bora155

    Joined:
    Mar 31, 2020
    Posts:
    12
    Hello I want to make it so when i use rigidbody2d.velocity and for example add 5 velocity on the x axis , it naturally adds 5 velocity on the x axis , simple . But what i want to do is i want to rotate the character with the E and Q buttons (Which ive already done) and when i press W to add velocity to my player , I want it to not add velocity towards the X axis but to the front of the player , how can I manage to do this

    Rotation Script :
    Code (CSharp):
    1. float rotationInput = Input.GetAxis("Rotation");
    2.  
    3. float rotationForce = rotationInput * Time.deltaTime * rotationPower
    4.  
    5. transform.Rotate(new Vector3(0, 0, rotationForce));
    Movement Script:
    Code (CSharp):
    1. moveInput.x = Input.GetAxisRaw("Horizontal");
    2. moveInput.y = Input.GetAxisRaw("Vertical");
    3. moveInput.Normalize();
    4.  
    5. rb.velocity = transform.up * moveInput.y * Time.deltaTime * moveSpeed * multiplier;
    Extra detail if you couldnt understand :

    So im gonna press W to go front , which works at 0 degrees angle because im my upper part is pointed towards the y axis so it adds 5 velocity to the y angle



    But when i rotate it to 45 degrees angle , it doesnt go forward of the player *blue arrow* but goes towards the y axis *black arrow*




    Thanks!
     
    Last edited: Jul 29, 2021
  2. bora155

    bora155

    Joined:
    Mar 31, 2020
    Posts:
    12
    I used this and it works . Here is the code if you wonder :

    Code (CSharp):
    1. float rotationInput = Input.GetAxis("Rotation");
    2.  
    3. float rotationForce = rotationInput * Time.fixedDeltaTime * rotationPower;
    4.  
    5. rb.MoveRotation(rb.rotation + rotationForce);
     
  3. bora155

    bora155

    Joined:
    Mar 31, 2020
    Posts:
    12
    Update : Changed the movement script .

    Replaced
    Code (CSharp):
    1. rb.velocity = transform.up * moveInput.y * Time.deltaTime * moveSpeed * multiplier;
    With
    Code (CSharp):
    1. rb.velocity = transform.up * moveInput.y * Time.deltaTime * moveSpeed * multiplier + transform.right * moveInput.x * Time.deltaTime * moveSpeed * multiplier;
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    No idea why you're scaling an absolute velocity by the elapsed frame-time as that makes no sense. Velocity is integrated during the simulation step (to give a new position) by the elapsed time. It might make sense if you were calculating acceleration etc but you're not.