# Getting the current 'Forward' direction Vector values into code and how to use them?

Im having some trouble visualising how the maths works for this particular problem. Back when i coded in 2d only this was often a stumbling point for mine even when only dealing with an x and y axis.

Here is the version of my current problem (but this is linked ot many other aspects of how my game will work , for example when I want to spawn a game object directly in front of the player for example):

1. Its a driving game where you have to drive along one long road until you get to the end. Of course there are going to be obstacles and enemies trying to stop you.

2. I'm using the Unity Standard Assets Car with some very small modifications to the control system only so far.

3. I want to proedurally generate the gameObjects (such as a ramp in the road, or an enemy at the side of road, or a cow in road for example).

4.I also would like a MPH counter (speedometer)

1. I can arrange all of this normally myself, but here's the thing, I can only do it on a straight road.
2. MY GAME NEEDS TO HAVE WINDING ROADS

So the way i normally calculate the MPH doesnt work I think, as it only works on 1 axis. If the players car is moving around a bend at 45d angle, then it would appear to be travelling much slower by my calculation than it actually is.

I think it must be calculated using the rotation, previousRotation, position, previousPosition and thats the route ive been exploring but i have failed to get anywhere and now my code is in a right mess. I am using the Unity Standard Car and I see in it's code that it has some math and uses the variable "forward", but im not sure how i can obtain a copy of that value, send it to my GameManager or Player script so that I can calculate where to put the obstacles etc onto the road exactly.

Most of the road is a nice straight road but there are some long bends too. I need some solid maths revision to get anywhere near calculating it myself and I just have a creeping feeling that half (if not more) of the work is already done for me inside this Unity Car Class.

I'll post the code here in case it helps: (Btw, its in the ApplyDrive method that im actually thinking the values i need are already there)

using System; using UnityEngine;

namespace UnityStandardAssets.Vehicles.Car { internal enum CarDriveType { FrontWheelDrive, RearWheelDrive, FourWheelDrive }

 internal enum SpeedType
{
MPH,
KPH
}
public class CarController : MonoBehaviour
{
[SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive;
[SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider;
[SerializeField] private GameObject[] m_WheelMeshes = new GameObject;
[SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects;
[SerializeField] private Vector3 m_CentreOfMassOffset;
[SerializeField] private float m_MaximumSteerAngle;
[Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing
[Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference
[SerializeField] private float m_FullTorqueOverAllWheels;
[SerializeField] private float m_ReverseTorque;
[SerializeField] private float m_MaxHandbrakeTorque;
[SerializeField] private float m_Downforce = 100f;
[SerializeField] private SpeedType m_SpeedType;
[SerializeField] private float m_Topspeed = 200;
[SerializeField] private static int NoOfGears = 5;
[SerializeField] private float m_RevRangeBoundary = 1f;
[SerializeField] private float m_SlipLimit;
[SerializeField] private float m_BrakeTorque;
private Quaternion[] m_WheelMeshLocalRotations;
private Vector3 m_Prevpos, m_Pos;
private float m_SteerAngle;
private int m_GearNum;
private float m_GearFactor;
private float m_OldRotation;
private float m_CurrentTorque;
private Rigidbody m_Rigidbody;
private const float k_ReversingThreshold = 0.01f;
public bool Skidding { get; private set; }
public float BrakeInput { get; private set; }
public float CurrentSteerAngle{ get { return m_SteerAngle; }}
public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}
public float MaxSpeed{get { return m_Topspeed; }}
public float Revs { get; private set; }
public float AccelInput { get; private set; }
// Use this for initialization
private void Start()
{
m_WheelMeshLocalRotations = new Quaternion;
for (int i = 0; i < 4; i++)
{
m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
}
m_WheelColliders.attachedRigidbody.centerOfMass = m_CentreOfMassOffset;
m_MaxHandbrakeTorque = float.MaxValue;
m_Rigidbody = GetComponent<Rigidbody>();
m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels);
}
private void GearChanging()
{
float f = Mathf.Abs(CurrentSpeed/MaxSpeed);
float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1);
float downgearlimit = (1/(float) NoOfGears)*m_GearNum;
if (m_GearNum > 0 && f < downgearlimit)
{
m_GearNum--;
}
if (f > upgearlimit && (m_GearNum < (NoOfGears - 1)))
{
m_GearNum++;
}
}
// simple function to add a curved bias towards 1 for a value in the 0-1 range
private static float CurveFactor(float factor)
{
return 1 - (1 - factor)*(1 - factor);
}
// unclamped version of Lerp, to allow value to exceed the from-to range
private static float ULerp(float from, float to, float value)
{
return (1.0f - value)*from + value*to;
}
private void CalculateGearFactor()
{
float f = (1/(float) NoOfGears);
// gear factor is a normalised representation of the current speed within the current gear's range of speeds.
// We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear.
var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed));
m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f);
}
private void CalculateRevs()
{
// calculate engine revs (for display / sound)
// (this is done in retrospect - revs are not used in force/power calculations)
CalculateGearFactor();
var gearNumFactor = m_GearNum/(float) NoOfGears;
var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor));
var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor);
Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor);
}
public void Move(float steering, float accel, float footbrake, float handbrake)
{
for (int i = 0; i < 4; i++)
{
Quaternion quat;
Vector3 position;
m_WheelColliders[i].GetWorldPose(out position, out quat);
m_WheelMeshes[i].transform.position = position;
m_WheelMeshes[i].transform.rotation = quat;
}
//clamp input values
steering = Mathf.Clamp(steering, -1, 1);
AccelInput = accel = Mathf.Clamp(accel, 0, 1);
BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0);
handbrake = Mathf.Clamp(handbrake, 0, 1);
//Set the steer on the front wheels.
//Assuming that wheels 0 and 1 are the front wheels.
m_SteerAngle = steering*m_MaximumSteerAngle;
m_WheelColliders.steerAngle = m_SteerAngle;
m_WheelColliders.steerAngle = m_SteerAngle;
SteerHelper();
ApplyDrive(accel, footbrake);
CapSpeed();
//Set the handbrake.
//Assuming that wheels 2 and 3 are the rear wheels.
if (handbrake > 0f)
{
var hbTorque = handbrake*m_MaxHandbrakeTorque;
m_WheelColliders.brakeTorque = hbTorque;
m_WheelColliders.brakeTorque = hbTorque;
}
CalculateRevs();
GearChanging();
CheckForWheelSpin();
TractionControl();
}
private void CapSpeed()
{
float speed = m_Rigidbody.velocity.magnitude;
switch (m_SpeedType)
{
case SpeedType.MPH:
speed *= 2.23693629f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized;
break;
case SpeedType.KPH:
speed *= 3.6f;
if (speed > m_Topspeed)
m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized;
break;
}
}
private void ApplyDrive(float accel, float footbrake)
{
float thrustTorque;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 4f);
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].motorTorque = thrustTorque;
}
break;
case CarDriveType.FrontWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders.motorTorque = m_WheelColliders.motorTorque = thrustTorque;
break;
case CarDriveType.RearWheelDrive:
thrustTorque = accel * (m_CurrentTorque / 2f);
m_WheelColliders.motorTorque = m_WheelColliders.motorTorque = thrustTorque;
break;
}
for (int i = 0; i < 4; i++)
{
if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f)
{
m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake;
}
else if (footbrake > 0)
{
m_WheelColliders[i].brakeTorque = 0f;
m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake;
}
}
}
private void SteerHelper()
{
for (int i = 0; i < 4; i++)
{
WheelHit wheelhit;
m_WheelColliders[i].GetGroundHit(out wheelhit);
if (wheelhit.normal == Vector3.zero)
return; // wheels arent on the ground so dont realign the rigidbody velocity
}
// this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction
if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f)
{
var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper;
m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
}
m_OldRotation = transform.eulerAngles.y;
}
// this is used to add more grip in relation to speed
{
m_WheelColliders.attachedRigidbody.velocity.magnitude);
}
// checks if the wheels are spinning and is so does three things
// 1) emits particles
// 2) plays tiure skidding sounds
// 3) leaves skidmarks on the ground
// these effects are controlled through the WheelEffects class
private void CheckForWheelSpin()
{
// loop through all wheels
for (int i = 0; i < 4; i++)
{
WheelHit wheelHit;
m_WheelColliders[i].GetGroundHit(out wheelHit);
// is the tire slipping above the given threshhold
if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit)
{
m_WheelEffects[i].EmitTyreSmoke();
// avoiding all four tires screeching at the same time
// if they do it can lead to some strange audio artefacts
if (!AnySkidSoundPlaying())
{
m_WheelEffects[i].PlayAudio();
}
continue;
}
// if it wasnt slipping stop all the audio
if (m_WheelEffects[i].PlayingAudio)
{
m_WheelEffects[i].StopAudio();
}
// end the trail generation
m_WheelEffects[i].EndSkidTrail();
}
}
// crude traction control that reduces the power to wheel if the car is wheel spinning too much
private void TractionControl()
{
WheelHit wheelHit;
switch (m_CarDriveType)
{
case CarDriveType.FourWheelDrive:
// loop through all wheels
for (int i = 0; i < 4; i++)
{
m_WheelColliders[i].GetGroundHit(out wheelHit);
}
break;
case CarDriveType.RearWheelDrive:
m_WheelColliders.GetGroundHit(out wheelHit);
m_WheelColliders.GetGroundHit(out wheelHit);
break;
case CarDriveType.FrontWheelDrive:
m_WheelColliders.GetGroundHit(out wheelHit);
m_WheelColliders.GetGroundHit(out wheelHit);
break;
}
}
{
if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0)
{
m_CurrentTorque -= 10 * m_TractionControl;
}
else
{
m_CurrentTorque += 10 * m_TractionControl;
if (m_CurrentTorque > m_FullTorqueOverAllWheels)
{
m_CurrentTorque = m_FullTorqueOverAllWheels;
}
}
}
private bool AnySkidSoundPlaying()
{
for (int i = 0; i < 4; i++)
{
if (m_WheelEffects[i].PlayingAudio)
{
return true;
}
}
return false;
}
}


}

As I say that is just standard Unity Assets code, but particularly in the ApplyDrive function i see the forward variable that I think will be useful (or hope :))

Any help on the best way to approach this kind of problem is massively appreciated. Sorry for the long-winded post. Thanks again for reading

m_Rigidbody.velocity is your movement vector.
m_Rigidbody.velocity.magnitude is the speed.
m_Rigidbody.velocity.normalized would be the normalized direction.

Note that units are in meters per second, which is why there's the CurrentSpeed property that returns it in miles per hour.

public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}


How would I use the normalize value above, to put into my GameManager class for example to say, when car is at Z position 150 on map, add Ramp 30 units IN FRONT OF THE CAR.

stop isolating the Z coordinate and use the entire vector!

class Car {
Vector3 position;
Vector3 velocity;
}

Vector3 ramp_position = car.position + 30.0f * car.velocity.normalized;


This says "start from the cars position, and offset it by 30 units in the direction of the car's velocity (i.e, which way it's moving)"

• thanks Jimmy. Sorry for being thick, but is normalized like this... is (rb.velocity.normalized.z * magnitude.z) the exact direction of going forward no matter whre you are facing with the external 3d world ? or will it need further calucations for this? Jul 19, 2017 at 18:42
• no. rb.velocity.magnitude is a number, the exact speed. normalized means basically the opposite of speed -- it means "a vector with constant magnitude" so basically, direction. if I'm doing northwest at 5 mph and you're going northwest at 500 mph, your velocity.magnitude is 100 times more than mine but our velocity.normalized are the same. Jul 19, 2017 at 18:47
• thank u, i do understand. But would the normalize.z be pointing in the direction of straight in front for my car? .......Im kind of forking off into another question, but all related really... How would I use the normalize value above, to put into my GameManager class for example to say, when car is at Z position 150 on map, add Ramp 30 units IN FRONT OF THE CAR Jul 19, 2017 at 18:49
• I guess a big part of my problem is how to use it in the code. Like referring to the position relative to the way the car is facing . Im sorry if I am not explaining properly Jul 19, 2017 at 18:51
• edited answer to explain the ramp question. Jul 19, 2017 at 18:55