Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by megabrobro · Jul 26, 2017 at 11:47 PM · unity 5vector3mathcarstandard-assets

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

Hi all, 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)

  5. I can arrange all of this normally myself, but here's the thing, I can only do it on a straight road.

  6. 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: (THANKS):

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[4];
     [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4];
     [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4];
     [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[4];
         for (int i = 0; i < 4; i++)
         {
             m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
         }
         m_WheelColliders[0].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[0].steerAngle = m_SteerAngle;
         m_WheelColliders[1].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[2].brakeTorque = hbTorque;
             m_WheelColliders[3].brakeTorque = hbTorque;
         }


         CalculateRevs();
         GearChanging();

         AddDownForce();
         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[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque;
                 break;

             case CarDriveType.RearWheelDrive:
                 thrustTorque = accel * (m_CurrentTorque / 2f);
                 m_WheelColliders[2].motorTorque = m_WheelColliders[3].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;
             Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up);
             m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
         }
         m_OldRotation = transform.eulerAngles.y;
     }


     // this is used to add more grip in relation to speed
     private void AddDownForce()
     {
         m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*
                                                      m_WheelColliders[0].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);

                     AdjustTorque(wheelHit.forwardSlip);
                 }
                 break;

             case CarDriveType.RearWheelDrive:
                 m_WheelColliders[2].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);

                 m_WheelColliders[3].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 break;

             case CarDriveType.FrontWheelDrive:
                 m_WheelColliders[0].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);

                 m_WheelColliders[1].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 break;
         }
     }


     private void AdjustTorque(float forwardSlip)
     {
         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

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image megabrobro · Jul 21, 2017 at 02:46 PM 0
Share

Why is this still in moderator hands? This is a fairly strange idea, as the problem has changed now in the 30+ hours since I posted it.

I dont get why it went to moderators? I didnt use a swear word or slang or anything so i dont get it. $$anonymous$$y other threads didnt go to moderators?

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by CheetahSpeedLion · Jul 27, 2017 at 03:26 AM

You need to use the transform.forward of the car. This will always be in the direction the car is facing.

You could either have the script on the car gameobjec itself or have any other gameobject reference it externally. For example, a "level generator" script that references the car.transform.forward.

Hope that helps, Areleli Games

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image megabrobro · Jul 27, 2017 at 03:14 PM 0
Share

thank you very much. Weirdly I was having to wait bout a week for this post to go thru moderation. (None of my others have had to wait !?!?)

$$anonymous$$eanwhile, I had written on another website and they mentioned Vector3.normalise.

I got fairly confused as to making things place in front of the car, mainly because the road has a fair few turns, and it does up n down on the Z axis too, so i ended up using many spawn points dotted about which have a random set chance of spawning said objects.

Your answer has helped me a lot as now I can check exactly how transform.forward works and perhaps can even combined that with Vector3.normalise if they dont do the same thing.

Thanks

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

141 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

[Math] Why is this possible ? 1 Answer

Average of Vectors [Math] 1 Answer

Rotate 3d vector based on local forward 1 Answer

Contributing back to Unit Standard Assets Package,Contributing fixes 1 Answer

Make something move away from click point. 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges