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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do you move a rigidbody relative to it's rotation

Discussion in 'Physics' started by PurpleDragon25, Sep 17, 2022.

  1. PurpleDragon25

    PurpleDragon25

    Joined:
    Jul 22, 2022
    Posts:
    2
    yo waddup, I'm fairly new to coding and trying to make a first person character using the rigidbody component but I'm not sure how to get it to move based on it's rotation, currently it's moving based on world coordinates. I'll have my current code attached. I would also appreciate it if I could get an explanation as to what's going on rather than simply a block of code that works.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RigidbodyMovement : MonoBehaviour
    6. {
    7.     public float speed = 5f;
    8.     Rigidbody playerRigidbody;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         playerRigidbody = GetComponent<Rigidbody>();
    14.     }
    15.  
    16.     // Update is called once per frame.
    17.     void Update()
    18.     {
    19.        
    20.         Vector3 userInput = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    21.         playerRigidbody.MovePosition(transform.position + userInput * Time.deltaTime * speed);
    22.  
    23.     }
    24. }
    25.  
     
  2. lightbug14

    lightbug14

    Joined:
    Feb 3, 2018
    Posts:
    446
    Hi,

    userInput is represented as a local (to the character) movement vector (XZ movement), so you need to convert that from local to world coordinates based on the current character orientation. One way to achieve this is like this:
    Code (CSharp):
    1. Vector3 userInput = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    2. userInput  =
    3.        transform.right * userInput.x +
    4.        transform.up * userInput.y +
    5.        transform.forward * userInput.z;
    Another way to do the same would be to use TransformVector or TransformDirection. Be careful, TransformVector gets affected by scale, which is not something that you'd normally want. Use TransformDirection instead:

    Code (CSharp):
    1. Vector3 userInput = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    2. userInput  = transform.TransformDirection(userInput);
     
  3. PurpleDragon25

    PurpleDragon25

    Joined:
    Jul 22, 2022
    Posts:
    2
    Thanks heaps, I've implemented the first one and it works a treat, and I'm pretty sure I understand what's going on as well