5

So I am struggling to realize how can I add velocity to a rb object relative to its rotation. Here is my script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using Cinemachine;
 
 [RequireComponent(typeof(Rigidbody))]
 public class PlayerController : MonoBehaviour
 {
     private Rigidbody rb;
     public CinemachineFreeLook camFreeLook;
 
     public float speed = 5f;
     private float refVelocity;
     
     void Start()
     {
         rb = GetComponent<Rigidbody>();
         Cursor.visible = false;
     }
     
     void Update()
     {
         float xMovement = Input.GetAxis("Horizontal") * speed;
         float zMovement = Input.GetAxis("Vertical") * speed;
 
         if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
         {
             rb.velocity = new Vector3(xMovement, rb.velocity.y, zMovement); // Here is the problem. It moves the player relative to the world axis, but im trying to move it relative to it's local axis
         }
 
         if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
         {
             float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y, camFreeLook.m_XAxis.Value, ref refVelocity, 0.1f);
             transform.eulerAngles = new Vector3(transform.eulerAngles.x, rotationY, transform.eulerAngles.z);
         }
     }
 }

Please if anyone knows how to fix this, add explanation. Thanks!

  • 1
    In general you shouldn't rotate your object like this. 1) Don't dynamically change [`eulerAngles`](https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html) 2) don't mix manipulation of Rigidbody with transform. Rather use e.g. [`Rigidbody.MoveRotation`](https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html) in fixed update – derHugo Dec 20 '20 at 17:46

1 Answers1

3

Use transform.TransformDirection to convert the direction from local space to world space:

rb.velocity = transform.TransformDirection(
        new Vector3(xMovement, rb.velocity.y, zMovement));
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
  • 1
    But wouldn't this be incorrect for the `Y` component since it already is in world space? ;) – derHugo Dec 20 '20 at 17:41
  • @derHugo In many cases yes, but if we can be sure that local y is the same direction as global y we can cheat a little ;) – Ruzihm Dec 20 '20 at 18:31