- Home /
Different drag for each axis
I'm currently working on a flying game. A problem I've been having so far is drag. If I set it too low, the plane "drifts" through the air. If I set it high enough to stop this behavior, the plane stops almost instantly when I turn off the engine. And of course, the plane doesn't gain speed from diving.
So what I figure that my game needs is for the plane to have separate drag values in all axis. Thing is, I'm not really sure how I'm supposed to do that.
So quite simply... how would I do that? Thank you in advance!
Answer by Bunny83 · Apr 03, 2017 at 04:11 AM
Rigidbodies are always simulated in worldspace. Therefore velocity is also a worldspace direction. You have to convert the velocity into local space, apply your localspace drag and convert it back to world space.
public class DirectionalDrag : MonoBehaviour
{
public float x;
public float y;
public float z;
Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void Update ()
{
Vector3 vel = transform.InverseTransformDirection(rb.velocity);
vel.x*= x;
vel.y*= y;
vel.z*= z;
rb.velocity = transform.TransformDirection(vel);
}
}
Answer by Hogge · Apr 02, 2017 at 10:15 PM
After doing some research on the forums, I've come across a method and written the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DirectionalDrag : MonoBehaviour {
public float x;
public float y;
public float z;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 vel = GetComponent<Rigidbody> ().velocity;
vel.x*= x;
vel.y*= y;
vel.z*= z;
GetComponent<Rigidbody> ().velocity = vel;
}
}
The thing is however, that when I test this, it seems like it works based on global axis, not local. In other words, when I adjust the values to be more than 1, the plane starts to fly in a different direction than it's pointing.
Answer by LeonmFF · Dec 21, 2020 at 01:40 PM
This is old and already have a solution, but I just can't help myself when I see an avoidable GetComponent in an Update function. Also, as we're are multiplying the values, I added a "1f +", so if you set the drag to 0 at the Inspector, it will still normally moves without drag. Set it to 0.2f and it will have a proper 0.2f drag.
You can also use this one:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class DirectionalDrag : MonoBehaviour
{
[SerializeField]
float _xDrag;
[SerializeField]
float _yDrag;
[SerializeField]
float _zDrag;
Rigidbody _rb;
private void Awake() => _rb = GetComponent<Rigidbody>();
void Update()
{
Vector3 t_velocity = _rb.velocity;
t_velocity.x *= 1f + _xDrag;
t_velocity.y *= 1f + _yDrag;
t_velocity.z *= 1f + _zDrag;
_rb.velocity = t_velocity;
}
}
Shouldn't we divide by drag instead of multiplying on it? In case when drag is of value 0.2f, the resulting velocity will be 1.2 times bigger while it should be theoretically 1.2 times lower.