Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to make a physically real,stable car with WheelColliders

Discussion in 'Editor & General Support' started by Edy, Jun 3, 2010.

  1. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    How to make a physically real, stable car using WheelColliders

    Demo:
    http://www.edy.es/dev/vehicle-physics/demo



    Press Enter to restart the level (i.e. if you flip the car or fall outside the terrain)
    Press C to change the secondary camera.
    Press B to change the stability mode among "Sport / Offroad" (default is "Sport")
    Press N to disable all stability features (keeps the plain rigidbody + 4 wheel colliders only). B to reenable.

    It's not only a typical road-car not meant to being too stable, but it also carries a heavy 500 Kg (1100 lbs) box! Can you keep it safely with you in all kind of terrains?

    Notes:
    - Simple PhysX model: rigidbody + some box colliders roughly resembling the car's shape + 4 standard WheelColliders
    - REAL center of mass, located around the front seats.
    - No angular drag, no arbitrary forces.
    - Default tyre friction curves, only stiffness is adjusted (forward: 0.82, sideways: 0.022)
    - No parameter is modified at runtime! (center of mass, rigidbody, drag or angular drag, suspension...)

    ---------------------------------------------------------------------------------------------------

    This is the typical stability problem when using WheelColliders:

    Q: Why my absolutely simple car (rigidbody + 4 wheel colliders) flips over so easily when steering?
    A: Because that's exactly how such car would behave in real life!!

    So you have created a box, added a rigidbody and four wheel colliders. Maybe you've even used some real car's data (mass, dimensions...). You have added a control script, tested it, and as soon as you gain a bit of speed and do a corner, the car rolls and flips over.

    If you could build that in real life, it would do the same! PhysX is not perfect, but resembles the physical behavior of real objects in a fairly good manner.

    Also note that the default WheelCollider's friction curve parameters in Unity (1,20000,2,10000,1) define a tyre with almost infinite grip. So the rigidbody has no choice but rolling-over when steering even at low speed. You should first set the last parameter (Stiffness Factor) to 0.01-0.03 to have more realistic tyres, but even in that case the car will roll over when stering at certain (low) speed.


    Q: But real cars don't roll over so easily. Why?
    A: Because real cars have STABILIZER BARS (aka anti-roll or anti-sway bars)

    http://auto.howstuffworks.com/question432.htm

    Sounds familiar?
    Stabilizer bars "link" the two wheels of the same axle allowing a limited degree of freedom between them. When one of the wheels is pushed upwards, the stabilizer bar transfers a portion of that compression force to the other wheel, so its suspension compress as well. This limits the roll of the body's car at that axle.

    Q: I haven't heard of such bars! Are really so important?
    A: Absolutely. Stabilizer bars are an essential part of a vehicle's suspension system in the same way as springs and dampers are.

    Look under your car, observe the suspension behind the front wheels. You'll be able to easily identify a rigid bar that travels from one wheel's suspension to another. That's it. The only exceptions are a very few car models that use dynamic systems (ej. computer-controlled hydraulic systems) to actively emulate the behavior of the anti-roll bars in turns.

    IMHO, an AntiRoll script for WheelColliders should be at least mentioned in the documentation and tutorials as a basic requirement for physically real vehicles. Actually, anti-roll bars are barely mentioned in the last chapter of the Unity's Car Tutorial (http://unity3d.com/support/resources/tutorials/car-tutorial), where an alternate car physics model is proposed.


    Q: What about all other solutions proposed here? (lower center of mass, angular drag, custom friction models...)
    A: The essential requirements for having a car that physically feels like real include the anti-roll bars.

    Once you have the REAL absolutely simple car (rigidbody + four wheel colliders + 2 anti-roll bars) you can then apply all other techniques to get special behaviors on your car and/or tweaking its handling, i.e for arcade-style driving.

    Even with the real absolutely simple car you'll find a lot of options to tweak and play with, all of them affecting the handling and feel of the car: mass, REAL center of mass (typically moved towards the engine location), front-rear springs, front-rear dampers (must be different because the axle under the engine will support more weight), front-rear anti-roll bar stiffness...

    No need for complicated custom friction/drag models at the beginning - leave them for final tweaks if necessary. You'll see how much the handling can change by simply adjusting the difference between the stiffness of the front and rear stabilizer bars.


    Q: What's bad with lowering the center of mass?
    A: Jumps, collisions, crashes or air-tricks will look weird because of the false center of mass.

    Artificially lowering the center of mass is just a workaround that works under some circumstances, but fails at others. Having the REAL center of mass in the car, and making it stable by means of stabilizer bars, will make almost all situations behave like real.


    Q: I've run your demo and I've made the car flip in "Sport" mode!
    A: Look at that kind of car. If you do a close turn at high speed with that car in real, surely you'd roll over as well!

    If you are (like me) used to watch those "educative" documentaries at Discovery Channel "Road Rampage", "Destroyed in Seconds", and so on, you'll know how easily this kind of cars can roll over at relatively normal speeds. Also, you may have heard about "The moose test", which is a heavy "S" turn test performed at 80 Km/h (50 mph). Many actual cars failed that test (Google for "the moose test" or see http://en.wikipedia.org/wiki/Moose_test)

    Note that in the demo the elevation of the center of mass is around the middle of the car's body! You must do a hard turn at around 60 Km/h (40 mph) for being able to flip the car in "Sport" mode. The anti-roll bars are doing an excellent work already.



    ---------------------------------------------------------------------------------------------------
    Now the fun part...

    Q: How to simulate stabilizer bars in Unity?
    A: Easily ;)


    Anti-roll bars work by transferring some compression force from one spring to the opposite in the same axle. The amount of the transfered force depends on the difference in the suspension travel among the wheels.

    So first task is to calculate the suspension travel on each wheel, as well as determine whether is grounded or not. We want the travel value to be between 0.0 (fully compressed) and 1.0 (fully extended):

    Code (csharp):
    1. groundedL = WheelL.GetGroundHit(hit))
    2. if (groundedL)
    3.     travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;
    4. else
    5.     travelL = 1.0;
    We multiply the travel diference by the AntiRoll value, which is the maximum force that the anti-roll bar can transfer among the springs (we could call this the Anti-roll bar's stiffness). This yields the amount of force that will be transfered:

    Code (csharp):
    1. var antiRollForce = (travelL - travelR) * AntiRoll;
    Finally, we must simply substract the force from one spring and add it to the other. We achieve this by adding opposite forces to the rigidbody at the positions of the WheelColliders:

    Code (csharp):
    1. if (groundedL)
    2.     rigidbody.AddForceAtPosition(WheelL.transform.up * -antiRollForce, WheelL.transform.position);  
    3. if (groundedR)
    4.     rigidbody.AddForceAtPosition(WheelR.transform.up * antiRollForce, WheelR.transform.position);
    Q: What's a good AntiRoll value? Which units is it expressed in?
    A: A good value is roughly the value of the wheel's spring. Both are expressed in Newtons.


    The spring value means the force the spring can give when fully compressed, and the AntiRoll value means the amount of force that can be transfered from one spring to another. Having the same values for Springs and AntiRoll in the same axle means that the anti-roll bar can transfer up the entire force of one spring to the other.


    Q: Can I have the script for an anti-roll bar?
    A: Sure, here is it.


    As suggestion, I believe that an Anti-Roll script should be included in Unity's Standard Assets.

    Add two anti-roll scripts to your vehicle, one per axle (front - rear). Set the left-right wheels on each one and adjust the AntiRoll value. Remember to reset center of mass to the real position, or don't touch it at all!

    The full script: AntiRollBar.js

    Code (csharp):
    1. var WheelL : WheelCollider;
    2. var WheelR : WheelCollider;
    3. var AntiRoll = 5000.0;
    4.  
    5. function FixedUpdate ()
    6.     {
    7.     var hit : WheelHit;
    8.     var travelL = 1.0;
    9.     var travelR = 1.0;
    10.  
    11.     var groundedL = WheelL.GetGroundHit(hit);
    12.     if (groundedL)
    13.         travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;
    14.  
    15.     var groundedR = WheelR.GetGroundHit(hit);
    16.     if (groundedR)
    17.         travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;
    18.  
    19.     var antiRollForce = (travelL - travelR) * AntiRoll;
    20.  
    21.     if (groundedL)
    22.         rigidbody.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
    23.                WheelL.transform.position);  
    24.     if (groundedR)
    25.         rigidbody.AddForceAtPosition(WheelR.transform.up * antiRollForce,
    26.                WheelR.transform.position);  
    27.     }

    Q: How can I set a real center of mass for my vehicle?
    A: Use non-overlapping box colliders to roughly resemble your vehicle's shape, then move the center towards the position of the engine.




    Unity/PhysX calculates the center of mass based on the position and volume of the GameObject's colliders. Note that overlapping colliders add more mass at the overlap position.

    Typically, you would only need to move the center of mass a bit towards the position of the engine (front - rear). For instance, if your vehicle has front engine and its front is oriented in the Z+ direction, you should only need to move the (automatically calculated) center of mass 1 meter to the front:

    Code (csharp):
    1. function Start ()
    2.     {
    3.     rigidbody.centerOfMass += Vector3(0, 0, 1.0);
    4.     }
    Q: Does it really works so good? Could it really be so simple??
    A: See it by yourself: http://www.edy.es/unity/offroader.html


    You can have a good view of how it works by pressing C (change secondary camera), then pressing B while driving (alternate Sport / Offroad mode). Press N for completely disabling the stabilizer bars (B to reenable, or Enter to restart after flipping over).

    ---------------------------------------------------------------------------------------------------

    Ending words....

    As this is my first post here, please let me introduce myself. I'm a developer now working on dj software. Years ago, while I was a student two friends and me spent about two years trying to develop games in C++ from scratch (no engines at all), because games was what we wanted to do since kids. As you can imagine, very little to no result could be seen in the screen. I discovered Unity about four weeks ago (had heard of it before, but hadn't look at it) and for me it was like seeing The Light. I could just put things on the screen, click play, and worked! I could then fine-tune the scene by looking at code examples and writing scripts in whatever language used by Unity (two weeks ago I realized I was coding in javascript). Magic! Now I'm about to achieve a personal goal of modeling physically real vehicles. This is what I really wanted to do since I was kid and self-learned to code in Basic with by Commodore 64. Overlander, Powerdrift, Hard Driving, and later 4D Sports Driving, Fatal Racing... now I can easily do it!! Even as hobbyist, I'm purchasing the Unity Pro license just because I love it!

    This article is my first contribution to the GREAT Unity community. It's great to have fun by modeling and playing with Unity's vehicle physics.

    Enjoy!
    Edy
     
    Last edited: Nov 7, 2017
  2. profcwalker

    profcwalker

    Joined:
    May 3, 2009
    Posts:
    243
    Thank you. That was a great read and a wonderful first post. :)
     
    haseebahmadd36 likes this.
  3. KevS

    KevS

    Joined:
    Apr 21, 2010
    Posts:
    51
    Thank you ! really !
     
  4. antenna-tree

    antenna-tree

    Joined:
    Oct 30, 2005
    Posts:
    5,324
    Wonderful post. I really appreciate you sharing your workflow and insights with this. Seems a shame to have this info lost in a forum thread. Maybe it can go up on the Unify Wiki or a blog post on the Unity blog page? Full credit to you of course ;)
     
  5. Guru

    Guru

    Joined:
    Apr 30, 2010
    Posts:
    118
    Awesome! I was racking my brain trying to figure out a way to increase stability back when I went through the Car Tutorial and was making my own for practice mini-racing game and Monster truck off-roading.

    This is a great solution to a problem that almost everyone seems to have when talking about vehicle physics. This definitely needs to be in the Wiki AND the blog! Great job! I will revisit that project and incorporate this into it as that was my biggest stumbling block.
     
  6. MitchStan

    MitchStan

    Joined:
    Feb 26, 2007
    Posts:
    568
    What a fabulous contribution. Sir, I tip my hat to you.
     
  7. KevS

    KevS

    Joined:
    Apr 21, 2010
    Posts:
    51
    I was vey happy yesterday when i find your topic, but today i'm disappointed. I tried to use your script to stabilizer my car, but it seems that nothing change (enabled or disabled) :(

    So i probably missed something (in spite of your very great explanation).

    These screenshots show what i have :

    Very basic shape :




    I tried to use real dimension for the differents elements :
    2m between rear wheels
    1.8m between front wheels
    3m between front wheels and rear wheels

    I tried to play with differents values for the mass/center of mass/spring/damping ... my vehicule flips to easily even at low speed.

    Maybe its a problem whith the scripts.

    Code (csharp):
    1. public class BuggyController : MonoBehaviour
    2. {
    3.  
    4.     public WheelCollider frontWheel1;
    5.     public WheelCollider frontWheel2;
    6.     public WheelCollider rearWheel1;
    7.     public WheelCollider rearWheel2;
    8.  
    9.     public float steerMax = 20f;
    10.     public float motorMax = 10f;
    11.     public float brakeMax = 100f;
    12.  
    13.     private float steer = 0f;
    14.     private float motor = 0f;
    15.     private float brake = 0f;
    16.  
    17.     void Start()
    18.     {
    19.         //rigidbody.centerOfMass += new Vector3(0f, 0f, -1f);
    20.     }
    21.  
    22.     void FixedUpdate()
    23.     {
    24.         steer = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1);
    25.         motor = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1);
    26.         brake = -1 * Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0);
    27.  
    28.         rearWheel1.motorTorque = motorMax * motor;
    29.         rearWheel2.motorTorque = motorMax * motor;
    30.         rearWheel1.brakeTorque = brakeMax * brake;
    31.         rearWheel2.brakeTorque = brakeMax * brake;
    32.         frontWheel1.steerAngle = steerMax * steer;
    33.         frontWheel2.steerAngle = steerMax * steer;
    34.     }
    35.  
    36. }
    And your script en C#

    Code (csharp):
    1.  
    2. public class AntiRollBar : MonoBehaviour
    3. {
    4.  
    5.     public WheelCollider WheelL;
    6.     public WheelCollider WheelR;
    7.     public float AntiRoll = 5000.0f;
    8.  
    9.     public void FixedUpdate()
    10.     {
    11.         WheelHit hit;
    12.         float travelL = 1.0f;
    13.         float travelR = 1.0f;
    14.  
    15.         bool groundedL = WheelL.GetGroundHit(out hit);
    16.         if (groundedL)
    17.             travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;
    18.  
    19.         bool groundedR = WheelR.GetGroundHit(out hit);
    20.         if (groundedR)
    21.             travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;
    22.  
    23.         float antiRollForce = (travelL - travelR) * AntiRoll;
    24.  
    25.         if (groundedL)
    26.             rigidbody.AddForceAtPosition(WheelL.transform.up * -antiRollForce,
    27.                    WheelL.transform.position);
    28.         if (groundedR)
    29.             rigidbody.AddForceAtPosition(WheelR.transform.up * antiRollForce,
    30.                    WheelR.transform.position);
    31.     }
    32.  
    33. }
    34.  
    If somebody can see where i'm wrong...
     
  8. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    Sure! Feel free to add the article to the blog and/or the Wiki. I'd be more than happy to appear in your blog! Take the version at the demo page as I've just updated the article. I believe this is a must-know for everybody modeling vehicle physics with Unity.

    Feel free also to correct any grammar or misspelling errors when publishing it. I'll then copy the corrections :p

    EDIT: The demo page will be the entry point for all my Unity articles and tutorials, so you can safely link it.

    Right now I working on the friction curves, how they work exactly, and how to configure and use them properly. I'm almost done with that, so I expect to update the demo during this week. The goal is to create a fully customizable GTA4-style car using standard components. A new article will follow some time later ;)
     
  9. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    @ProfCWalker, Guru, MitchStan:

    Thank you very much! Hope you have as much fun modelling vehicles as I'm having while (still) discovering Unity :)

    @blizhard:

    Thank for your comments! There's one obvious problem in your project, and other minor things you should consider. The big obvious thing:

    Code (csharp):
    1. Sideways Friction > Stiffness Factor: 1
    Change that value to 0.02 - 0.01 in all wheels. Use that value to fine tune the "drifting" ability.
    My next article will explain everything about the friction curves ;)
    EDIT: I've updated the post to include the stiffness values used.

    Other things to look at:

    - The radius of the wheels are too large. Use something more realistic, about 0.5. Note that actually they are increasing the vehicle's height a lot.

    - You have a very big collider at the top of your "car". This makes the auto-calculated center of mass to be very high. You should move the center of mass to a more realistic position. Somewhere at the top of the lower colliders should be ok.
     
  10. psychicparrot

    psychicparrot

    Joined:
    Dec 10, 2007
    Posts:
    884
    VERY cool - nice work thanks for sharing the info (and the code!) :D
     
  11. KevS

    KevS

    Joined:
    Apr 21, 2010
    Posts:
    51
    @Edy : Thank you man ! it works !!
     
  12. eskovas

    eskovas

    Joined:
    Dec 2, 2009
    Posts:
    1,373
    Hi there,
    great physics you have there.
    i'm making an open world game (like GTA) and started doing the car physics about 1 week ago...
    i'm having some problems with the physics and i hope you or anyone could help
    here is a small video of the problem:
    http://www.youtube.com/watch?v=TVfaHqBdKt0
    at medium speeds, if i turn the car it will flip...
    i would apreciate any help

    i also used your script but it still flips:
    here are the properties of the wheel colliders and other things:





    (also i sent you a PM, hope you read it)

    Edit:
    i changed the stiffness factor of the sideways driction to 0.02, and now it turns better and doesn't flip, but at high speeds it still flips...
     
  13. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    Recently I've realized that the WheelCollider has a design problem on the sideways friction. For any stiffness value, there will be a speed at which the car will flip over.

    So your chance is to set a speed limit to the vehicle, and then find a stiffness factor so low that the car doesn't flip over at that maximum speed. You could also try dynamically setting the stiffness factor according to current speed.
     
  14. Alex Mat

    Alex Mat

    Joined:
    May 14, 2010
    Posts:
    177
    I don't think it's really a design problem,or maybe just a bit, since in real cars the tire warms on slidings and loose traction.

    Try it by yourself: Take a small 1:10 car which has replica of tires (must be enough realistic replica) and try to move it on the side pushing it to the ground. You'll see the car will hardly slide.


    But maybe I'm wrong.
     
  15. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    It's a design problem, trust me. I've researched deep in the WheelCollider's insights and the sideways friction behaves in a way that it's barely usable as-is. You'll see it more clearly when I publish the information and documents.
     
  16. Alex Mat

    Alex Mat

    Joined:
    May 14, 2010
    Posts:
    177
    That's what I was saying, the wheel collider in Unity is given as a plastic toy's wheel, you must simulate some kind of warming to get the desired effect. :p
     
  17. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    The new forum system doesn't let me edit the original post (>10000 characters, odd). So here's the update:



    New in this version:

    • Highly improved everything.
    • 4 vehicles: V3 Pickup / GTA4 Pickup / Bus / Sport Coupe (select with PgDown / PgUp).
    • Dashboard with speed, gear, and driving aids (1-5 for driving aids)
    • New damage script with improved deformation and instant-repair option (shift R).
    • Vehicle interiors with mouse-look view (F1, mouse look where available).
    • Rear mirrors in the Bus driver view (PgDown until Bus, then F1).
    • Better traction simulation at low speeds (burnouts without TC).
    • Smoke effects on burnouts and driftings.
    • WheelCollider friction curves are now perfectly predicted, allowing exact fine-tunning of the tire behavior.
    • Graphic tire telemetry (B, then shift-B)
    • Integrated help (H).
     
  18. jeffmorris

    jeffmorris

    Joined:
    Nov 26, 2009
    Posts:
    144
    I like Edy's vehicle library better than other vehicle libraries. Is it possible to get source code and content so that I can create my driving/racing games?
     
  19. spectre1989

    spectre1989

    Joined:
    Oct 6, 2009
    Posts:
    125
    I'd really like to see some source code for this demo, I just can't get my cars to behave the same!
     
  20. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    I would like to purchase an asset bundle for this. Can you make it available at a (hopefully not expensive) price? Its just the right feel.
     
  21. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    No matter what I do my car flips when moving *forwards*. What am I missing?
     
  22. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    @spectre1989,

    Thanks for your message! I believe that it's better to answer your PM here, as yours is a common problem when building vehicle physics in Unity: the vehicle rolls over too easily above a certain speed.

    The problem is that the WheelCollider in Unity has a design flaw that greatly increases the sideways friction with the speed. The workaround is to set a speed limit to your vehicle, then find a good combo of sideways stiffness + height of the center of mass + anti-roll bars stiffness that keeps your vehicle stable when sliding laterally at its maximum speed. Try starting with a sideways stiffness of 0.04, and use values between 0.02 and 0.06. You can get fairy good results this way.

    I've been able to fully identify the WheelCollider's design flaw and counteract its effects in scripting. This is why my vehicles behave correctly at any speed.

    If you don't know, I'm participating with my demo in this contest:
    http://forum.unity3d.com/threads/47...rial-GTA4-Vehicle-Replica-Project-4050/page29

    (see the first page for the contest rules)

    After the contest come to an end, I plan to disclose the information on this flaw so anyone could learn to use WheelColliders properly. I can't tell about the project source, as that depends on the result of the contest (I may be limited by the contest's conditions if I win).
     
  23. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,495
    WheelColliders: forwardFriction.stiffnessFactor is still too high. Use values from 0.02 to 0.08. Also, scale down the values you're setting at motorTorque / brakeTorque. Do not try to use real units here, just trial error until you find good working values.
     
  24. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Thanks that was it Edy :)
     
  25. spectre1989

    spectre1989

    Joined:
    Oct 6, 2009
    Posts:
    125
    Thanks Edy I'll try that =)

    Good luck in the competition!
     
  26. Mani

    Mani

    Joined:
    Jan 12, 2009
    Posts:
    117
    I just saw this for the first time. Very informative stuff! Thanks for taking the time to put this together.
     
  27. Kashif Amin

    Kashif Amin

    Joined:
    Oct 28, 2010
    Posts:
    30
    Dear All,

    I am working on homemade 3 DOF motion platform to with i wish to interface Unity3d Car Tutorial Game Or any other racing game.

    Kindly help me how to interface motion platform with unity. I want to know how unity3d gives output to the port so that i can sychronise motion behaviour of the game vehicle to my home made motion platform.

    Thanks
     
  28. Fengol

    Fengol

    Joined:
    Feb 10, 2011
    Posts:
    1
    Is there any idea when the competition will end or the source made available? I'm really struggling to get my car going nicely
     
  29. carking1996

    carking1996

    Joined:
    Jun 15, 2010
    Posts:
    2,608
    Yes. I would like the source! It would be amazing for my racing game. ;)
     
  30. Afisicos

    Afisicos

    Joined:
    Nov 13, 2010
    Posts:
    326
    nice. i will try to make a car
     
  31. Reint Jan

    Reint Jan

    Joined:
    Dec 5, 2011
    Posts:
    2
    Thanks a lot Edy for sharing this knowledge. I'm just starting out with unity, i choose to go with C# because of my previous experience with C#. I'm making a little race game for my university course. but i ran in to some questions. i hope you can help me with them.

    How can i make a reverse. i can think of 2 ways but i think its not the correct way of doing so. i could rotate the wheel colliders( but this is just a cheat) , i also tried to give it a negative motor Torque but this doesn't seem to affect the car. i believe i missed something do you have any hints / tips on this subject.

    Today i'm looking in to the anti-roll because i could get it to work yet, i suspect this comes down to a lack of experience :p
     
  32. jocoUnity

    jocoUnity

    Joined:
    Oct 2, 2011
    Posts:
    25
    Love this package! Nice work Edy!

    I'm trying to convert it over for touch control.

    I can't seem to find any where in the scripts that map the arrow keys to move the cars.

    Anyone know which variables/scripts I can control with touch to actually move the cars?
     
  33. Reint Jan

    Reint Jan

    Joined:
    Dec 5, 2011
    Posts:
    2
    Where you are looking for is something like this (C# script).
    Code (csharp):
    1.  
    2.     public float steerMax = 20f;
    3.     public float motorMax = 10f;
    4.     public float brakeMax = 100f;
    5.  
    6.     private float steer = 0f;
    7.     private float motor = 0f;
    8.     private float brake = 0f;
    9.  
    10.     void FixedUpdate()
    11.     {
    12.         steer = Mathf.Clamp(Input.GetAxis("Horizontal"), -1, 1); //<------ Steering
    13.         motor = Mathf.Clamp(Input.GetAxis("Vertical"), 0, 1); //<------ Forward Movement
    14.         brake = -1 * Mathf.Clamp(Input.GetAxis("Vertical"), -1, 0); //<------ Braking
    15.  
    16.  
    17.        //Over here you add the Force to a wheelcolider.
    18.  
    19.         rearWheel1.motorTorque = motorMax * motor;
    20.         rearWheel2.motorTorque = motorMax * motor;
    21.         rearWheel1.brakeTorque = brakeMax * brake;
    22.         rearWheel2.brakeTorque = brakeMax * brake;
    23.         frontWheel1.steerAngle = steerMax * steer;
    24.         frontWheel2.steerAngle = steerMax * steer;
    25.     }
    26.  
    27. }
     
  34. rockysam888

    rockysam888

    Joined:
    Jul 28, 2009
    Posts:
    650
    (bookmarked)
     
  35. dantheman221

    dantheman221

    Joined:
    Jan 8, 2012
    Posts:
    2
    Hey Edy, I like the scrip! :D Only issue I have is, the cams dont work for some reason and the spedometer and everything else is not working. Car moves.....i think xD I have almost exactly the same hierarchy like your demo does Still doesn't work -__- Its v 4.2 btw.. Plus, Skidmarks don't work -__-
     
    Last edited: Jan 10, 2012
  36. Sequence

    Sequence

    Joined:
    Feb 4, 2012
    Posts:
    44
    Awesome! Thanks so much for sharing this.
     
  37. GBCFraser

    GBCFraser

    Joined:
    Apr 11, 2013
    Posts:
    94
    Very well done tutorial. Alot of things I did not know.
     
  38. Sandro-7

    Sandro-7

    Joined:
    May 25, 2013
    Posts:
    6
    Hello,
    I'm an happy user of your vehicle @Edy, it is amazing!
    Now I need to enter exit from the vehicle. Basically I used some tricks and seems they work, but is not perfect.
    Instead, please can you suggest me the best way to achieve this? Is there any way to enable/disable vehicle driving, activation of Audio Listener, etc... ?

    Thank you!
     
  39. zardini123

    zardini123

    Joined:
    Jan 5, 2013
    Posts:
    68
    Absolutely magnificent!

    Enough said...
     
  40. zardini123

    zardini123

    Joined:
    Jan 5, 2013
    Posts:
    68
    You can do that by enabling the car script you have and/or the wheel colliders inside a script to stop the car
     
  41. rameshkumar

    rameshkumar

    Joined:
    Aug 5, 2013
    Posts:
    50
    how to get this project.where to download this project.help me dude..:(
     
  42. zweihander111

    zweihander111

    Joined:
    Nov 7, 2010
    Posts:
    20
    Wow, really impressed for such amount of work and dedication. I'm also willing to pay a reasonable amount of money for the source code. Wouldn't you consider selling on the asset store? (Please forgive me if this subject has already been discussed)
    Thank you for both the demo and info!
     
  43. AndyB_1992

    AndyB_1992

    Joined:
    Sep 18, 2012
    Posts:
    1
    I just wanna know how you did the damage/repair features, its so cool watching the car repair itself. I have no clue how you've managed it. Amazing work.
     
  44. EnriqueD

    EnriqueD

    Joined:
    Nov 20, 2013
    Posts:
    1
    Thank you!!
    This is a great post!!
    And what changes are needed for making a bicycle?
     
  45. yacoj17

    yacoj17

    Joined:
    Mar 16, 2014
    Posts:
    1
    This was an awesome thing. Hey i was just wondering, how to make my car controllable in the air because I'm trying to make a car stunt game but when its in the air, i can't control it do do flips and stunts. Pls help
     
  46. Nition

    Nition

    Joined:
    Jul 4, 2012
    Posts:
    781
    It's a tutorial. Edy isn't giving away his whole project, but he provides the code and the information necessary for you to replicate the basics yourself in the first post.
     
  47. Runalotski

    Runalotski

    Joined:
    Mar 4, 2014
    Posts:
    10
    Hello

    I have been messing around with wheel colliders abit to try and make a tank that moves nicly I thought wheel colliders would be the way foward.

    However I have problems making it travle in a straight line even though all the wheel have the same torque applied and are equal distance from the center of mass, reducing the sidways slip is possible but then it becomes impossible to turn using classic tank controls,which requies sidways slip on the colliders at the back and front, there are other ways to fake that i know will work but do not have the correct feel in all situations.

    I added your script to see if the forces balance out when the suspention is stablaized but had no affect.

    it is hard to tell withough the data in the inspecter but do the vehicals int he demo aslo do this but only slight or do the go in a perfactly straight line if only "foward" is held down?

    Any advice would be apriciated.
     
    Last edited: Apr 22, 2014
  48. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Brilliant read, very infomative.
    im trying to get my head round the wheel colliders and simple car physics, this definetly helped alot.
     
  49. RedTwentyFour

    RedTwentyFour

    Joined:
    May 9, 2013
    Posts:
    2
    thought about it a bit, since i am a fan of shorter code...wouldnt this work also, for both axles, in a shorter, quicker way? (untested.)

    suppose that alllwheels[] are WheelColliders for FrontLeft, FrontRight, RearLeft and RearRight rspectively...

    Code (CSharp):
    1.    
    2. WheelHit hit;
    3. float[] travel = newfloat[] {1.0f, 1.0f, 1.0f, 1.0f};
    4. float antiRollForce = 0.0f;
    5.  
    6. for (inti = 0; i < allWheels.Length; i++) {
    7.  
    8.    WheelColliderwheel = allWheels[i];
    9.    boolgrounded = wheel.GetGroundHit(outhit);
    10.  
    11.    if (grounded) {
    12.       travel[i] = (wheel.transform.InverseTransformPoint(hit.point).y - wheel.radius) / wheel.suspensionDistance;
    13.  
    14.       if (allWheels[0] || allWheels[1]) {
    15.          antiRollForce = (travel[0] - travel[1]) * 5000;
    16.       } elseif (allWheels[2] || allWheels[3]) {
    17.          antiRollForce = (travel[2] - travel[3]) * 5000;
    18.       }
    19.  
    20.       rigidbody.AddForceAtPosition(wheel.transform.up * antiRollForce, wheel.transform.position);
    21.  
    22.     }
    23.  
    24. }
    25.  
     
  50. RevolutionNow

    RevolutionNow

    Joined:
    Oct 12, 2013
    Posts:
    8
    Hi Thanks for the tutorial but I can't seem to get it to work properly. I have the AntiRoll variable set to about 500 but when I try to turn it shakes the car alot.
     
    Last edited: Nov 1, 2014