Making Custom Car Physics in Unity (for Very Very Valet)

Estimated read time: 1:20

    AI is evolving every day. Don't fall behind.

    Join 50,000+ readers learning how to use AI in just 5 minutes daily.

    Completely free, unsubscribe at any time.

    Summary

    In this video, Toyful Games unveils their process for creating custom car physics in their game "Very Very Valet" using Unity. They emphasize the importance of developing your own mechanics if they are central to your game, to maintain control and flexibility throughout development. The video meticulously breaks down the techniques used to simulate car physics, ranging from basic arcade to semi-realistic handling. It introduces a raycast-based approach for simulating the car's movement by calculating forces for each tire related to suspension, traction, and acceleration. Through visualizations and in-depth explanations, the video explores the intricacies of managing various forces to achieve the desired car behavior. The creators offer a comprehensive look into their coding strategy, showcasing the simplicity behind what may seem complicated at first glance.

      Highlights

      • The creators emphasize the importance of coding your own game mechanics if they're central to your game 🎮.
      • A raycast-based approach is used for simulating car physics, involving one main rigid body 🏎️.
      • Each tire's forces are broken down into suspension, traction, and acceleration ⚙️.
      • Visual demonstrations and coding strategies reveal the simplicity behind complex calculations 📊.
      • Their game, 'Very Very Valet', is available on Nintendo Switch, Steam, and PlayStation 5 🎮.

      Key Takeaways

      • Code mechanics if they are central to your game to maintain control 🛠️.
      • Raycast-based approach simplifies car physics by using one rigid body 🚗.
      • Break down tire forces into suspension, rolling, and steering for precision 🛞.
      • Use damping for realistic suspension forces, ensuring cars don't bounce endlessly 🤔.
      • Tune car behavior through adjustable parameters for suspension, grip, and power curves 🎮.

      Overview

      In creating their fun couch co-op game, Toyful Games stress the value of coding your core mechanics, like car physics, to retain control and adaptability as the game develops. They share their unique approach using raycasts and forces to simulate vehicle movement within Unity.

        Exploring beyond the visual complexity, they break down the car's physics into manageable forces at each tire — suspension, traction, and drive. Through clever visualizations, the creators impart how these combined forces create a driving experience that ranges from mighty arcadey to semi-realistic handling.

          For enthusiasts interested in game development, the video offers a detailed walkthrough of coding these forces, presenting adaptive strategies for tuning car behavior. Their showcased game 'Very Very Valet' reflects these precise mechanics, available across major gaming platforms.

            Making Custom Car Physics in Unity (for Very Very Valet) Transcription

            • 00:00 - 00:30 so we're making a couch co-op game about being valets we wanted to make sure we had complete control of the feel physics and the amount of realism in our cars and our line of thinking is if you have a mechanic in your game central to your game and you have the skills to code it yourselves you should code it yourselves that'll give you complete control to modify it and adjust it as your game evolves over the course of development in this video we're going to go over step by step all the ways we calculate the forces required to make custom car physics in unity all right welcome to our car test facility let's take a look at one of the
            • 00:30 - 01:00 cars from the game here so prim will give us a little demonstration of the handling of this uh high quality sedan here you can see we went with a pretty arcadey kind of bouncy feel to the cars but the the techniques we're going to talk about today will actually work for simulating arcadey all the way to semi-realistic cars all right let's hop in the little test mobile here and talk about how these cars work in detail so the first thing to mention out of the gate is that we went with a raycast based approach so that means that rather
            • 01:00 - 01:30 than actually simulating an individual rigid body for the main car and then an individual rigid body for each tire and connecting them with some kind of physics joints or something there's actually only one rigid body going on here so this is what this car looks like according to the physics system it's somehow one rigid body that seems to be driving around as though it is has tires and then works like a car and so that's actually what's going on here is that we are creating forces that we're applying to this one rigid body to
            • 01:30 - 02:00 make it behave like a car that has tires attached to it here's a look at those forces you can see that there's four of them so basically at the location of each tire we're using raycasts to find the ground underneath us and then working out things like suspension and friction forces and applying them to the main rigid body of the car at the location of each tire and then the net result of these four forces is a single rigid body that drives around like a car so you should be on the right track now you know cast some rays calculate a force for each tire and you've got a
            • 02:00 - 02:30 raycast car thanks and don't forget to like and subscribe okay obviously i'm going to go into more detail because look at these forces they look totally confusing and complex like how are these being calculated what kind of crazy math is going on to make these wild forces that are constantly changing direction and changing their magnitude and like oh my gosh i don't even know where to get started well the good news is that while this looks really complicated we can break this problem down and make it significantly simpler and the first thing to realize is that
            • 02:30 - 03:00 the tires are basically like children of the car and so what we did is we created four transforms that we attached to the car that represent sort of like the location of each wheel if we look at one up close we can see that actually we can think of a tire as actually having three individual forces that contribute to its effect on the car and if i turn on a little visualization of these we can see them independently so here in the green direction we have suspension
            • 03:00 - 03:30 so if prim bounces up and down on the car we can see that the force in the green direction that is the suspension is sort of growing and shrinking depending on how much it needs to push to keep the car uh floating above the ground and then in the blue direction you have gas and break so you can see a force in the blue direction is the direction that the tire likes to roll in and so here if we push a force in the blue direction we can speed up the car or we can slow down the car and apply brakes
            • 03:30 - 04:00 and then finally you have that red direction which represents steering or sort of slipping so if the tire was moving in the red direction that would be bad right tires don't like to slip so what we end up doing is calculating a force in the red direction that reduces slipping and says i don't like to be moving in this direction stop any movement in this direction i like to move in the blue direction but not in the red direction and we can think about these things separately so actually each tire on this car is actually just three numbers that we need
            • 04:00 - 04:30 to calculate we need to calculate a number for the green force that says what's the suspension doing we need to calculate a number for the blue force that says what are we doing for rolling and accelerating and breaking and we need to calculate a number for the red direction that says how do we make sure we're not slipping and we're actually steering and rolling in the direction we want and so that's what we're going to spend the rest of this video doing is actually breaking down this problem into just three separate numbers that we calculate independently and once you calculate
            • 04:30 - 05:00 that you get the sum of all those forces and that is the result for each tire okay let's start with the green force we were talking about before which is the suspension force which is basically there's a spring attached to the tires that is holding the car up off the ground and of course we're talking about a spring here so we're going to need to calculate a spring force now the first thing to realize about a spring is that a spring has a rest distance it has a length that it likes to be and then if you compress the spring it
            • 05:00 - 05:30 will push back to go back to the rest distance or if you stretch the spring it will pull back to go back to that rest distance and so the first number that's involved in this calculation is going to be the offset which is basically just how far away are we from that rest distance now notice that this offset needs to be assigned value so on one side it needs to be negative and on the other side it needs to be positive and this number is telling you which way to go and how far to go to get back to the rest distance
            • 05:30 - 06:00 and actually if you want to calculate a spring force that's really all you need you need to know the offset and then you multiply that by some value that says how strong is this spring so here's a quick example where we set the strength to 10 and if we push the spring and then let go you can see this green line let me uh scale it down so it's easier to see on the screen the green line is the force we're calculating and the force is literally just the current offset times some number which represents the strength of the spring so when we're
            • 06:00 - 06:30 pushed all the way here to an offset of negative point four then our force is negative four and if i stretch the spring the other way we get a force just as strong in the opposite direction and then you can start playing with values like this value for strength what if we beef up the spring and give it a much thicker metal coil now you can see the force is a much higher value and that results in a much faster oscillation so the first step to calculating a spring force is just to calculate the
            • 06:30 - 07:00 offset and multiply it by the strength of the spring that gives you a force that you can apply directly but you might be noticing that this spring seems to just bounce back and forth forever and that's true if you just have this much information you get a spring that will bounce forever now real shocks on cars and other kinds of springs have what's called a damper it looks something like this they're sort of like a plunger of some kind and there's some fluid and then this thing doesn't want to move so when you try to push the spring now
            • 07:00 - 07:30 it has to push the plunger through that fluid which is resisting motion and so that's literally what damping is referring to is trying to slow down the motion of the spring so we can represent this in code if we know one other thing if we know the current velocity of the spring so imagine the spring's bouncing back and forth we can stop it at any point and we can understand the velocity of the object the spring is attached to in this case the tire and if we know that we can calculate a
            • 07:30 - 08:00 damping force so a damping force is basically trying to stop any motion it wants to resist motion so that's why you take velocity into account and so if i give this thing a little nudge here you can see that it quickly kills any motion and this is happening with a force that's in the opposite direction of the velocity so the velocity is headed to the left and the force is pushing to the right and the size of the force is sort of relative to how much velocity we have
            • 08:00 - 08:30 you can see down there the force is just negative velocity times damping and again damping is just some number that we choose in this case you can think of damping as kind of representing how thick is the fluid that's inside that damper there thicker the fluid the more it's going to resist motion so then when we want to calculate a better spring we combine these two elements so now our force is equal to the offset times the strength which is the part that's trying to push the
            • 08:30 - 09:00 spring back to its rest distance and then we tack on this damping component says but by the way this spring is resisting motion and so now when i compress the spring and i let it go you see we don't oscillate very much in fact we come to rest very quickly so it starts to get a little complicated to look at all these arrows and kind of like really understand what's happening but if i slow down a little bit you can see that at the beginning here when the spring was squished and we let go
            • 09:00 - 09:30 that we have our offset is pretty big and that times the strength is giving us a lot of force saying go to the left and right now our velocity is pretty small so it's not doing much but as we speed up here and we head towards the home position look at that our green force actually flipped directions and despite the fact that the spring still needs to go to the left to reach its rest position our ultimate force right now is pushing in the other way it's trying to slow this thing down slow down slow down
            • 09:30 - 10:00 slow down so that's the damping force counteracting the regular spring component to keep this thing from oscillating over and over again what's great about this is once you've got this formula it's just four numbers offset times strength minus velocity times damping two of these numbers are numbers you just decide the strength and the damping and you get very different behaviors depending on what you set these numbers to here's an example of a spring with a strength of 100 and a damping of one so
            • 10:00 - 10:30 this thing is going to bounce back and forth a lot because the damping is not is very small it has a small effect on the system this would be like a spring with a really thick coil of metal and maybe just air inside the plunger now what if we change this and we say the damping is 30. we took the air out of the plunger and we just poured a bunch of honey in there and so now this spring really is not going to want to move so even if i compress it down and let it go with the same strength coil it has to try really hard to push that
            • 10:30 - 11:00 spring because it's really resisting any kind of motion and maybe somewhere in the middle let's take out that honey and put oil inside and now you get something that doesn't resist it too much lets it get right back to the rest position but it doesn't overshoot very much and so these are two numbers that you can then tune to get a spring to behave exactly how you'd like now one thing to keep in mind is that these numbers are relative to the mass involved so imagine you had a really weak spring and you put it on a car the car would just slam down to the ground because it was so heavy
            • 11:00 - 11:30 similarly here depending on the mass of the objects that you're trying to affect with this spring you might have to make the strength and the dampening bigger or smaller depending on the mass involved so here we have again our final formula for a spring force and this is what is called a dampened spring force because it has the damper involved but basically it's just four numbers you got to work out the offset how far away are we from our rest distance multiply that with the strength of the spring and then subtract
            • 11:30 - 12:00 the velocity of the thing the spring is attached to in the direction of the spring by the way times the damping and then you get a spring force so this is all we need to calculate that green force on our car and here's a look at the actual code for the suspension force and as you can see this formula is basically implemented directly in the code we do some setup to work out things like our offset and our velocity but then we plug those in and we have our formula right there offset
            • 12:00 - 12:30 times strength minus velocity time stamping and then that force is applied at the position of this particular tire okay so here's a look at a car with just those green suspension forces implemented and you can see we're able to keep the car up off the ground now um but if we bump into the car and send it moving we've got shocks but we have absolutely no traction whatsoever so good job we made a hovercraft
            • 12:30 - 13:00 okay so as the car is driving along here what we can do is we can zoom in on each individual tire and get the velocity of that individual tire which is just the velocity of that point on the car's rigid body and then we can break this up into our blue and our red directions so the blue direction of course is the direction the tire likes to roll and the red direction is the direction the tire doesn't like to slide so we can take the current velocity for each tire which in this case is this orange arrow and we
            • 13:00 - 13:30 can use a dot product to break it up into two separate components the component that's going in the rolling direction the blue direction and the component that is in the sliding direction and now we're going to currently focus our attention on the red direction because that's the force we're calculating right now it's going to produce steering so if we just think about this this is the current velocity of the tire in the direction of the red line the direction we don't want to be sliding
            • 13:30 - 14:00 and so we're going to need to calculate some sort of force that says don't slide in this red direction right ultimately we don't really want any velocity in the red direction because that velocity means the tire is slipping sideways so we're going to calculate some kind of force for this and force of course is mass times acceleration so if we want a force we can think about it in terms of an acceleration and an acceleration is just a change in velocity so what we can do is ask
            • 14:00 - 14:30 ourselves what change in velocity would we like to occur well actually that's pretty straightforward because we currently have this gray line that is the current velocity in the direction of the red sliding direction and we don't want any of that velocity to exist we don't want to slide sideways so really what we want is a change in velocity that is the opposite we want to remove all of this velocity so if we just take that current velocity and flip its direction that's the change we would like to have
            • 14:30 - 15:00 occur and at this moment when we flip it we could also for example scale it down a little bit and say well we're okay with the tire sliding a little bit so maybe we're only going to try and remove 50 percent of the velocity or the car should be sliding a lot right now we're on ice so let's only remove maybe 10 of the velocity but basically what we're going to do is we're going to take the current velocity of the tire in the sliding direction and we're going to flip it around and that then is a change in velocity that we want to have happen so
            • 15:00 - 15:30 we take that vector we divide it by some amount of time a small amount of time to say this is the acceleration we want we want a change in velocity over time and then that value becomes our force so here you can see if we just take the velocity in the red direction and we completely negate it and use that as our force here's a here's a car example with 100 grip and you can see the tires do not like to slide and of course they're so grippy that maybe the
            • 15:30 - 16:00 car will flip over depending on things like the center of mass now here's an example where we're only um canceling out five percent of the slip velocity and now you can see we've got real slidey car this is a front-wheel drive car by the way so it's not going to spin out too much but it is really slidy and now now we've made a drifting game just by saying we have basically five percent traction in the red direction and then here's another example where now the front tires have 30 grip the
            • 16:00 - 16:30 rear tires have five percent grip and it's a rear-wheel drive car and now you can see this car really likes to spin out i'm not even steering right now we're still doing donuts and so uh you know this gives you a lot of control over the car that you can think of in simple turns of in simple terms of just how much grip do we want to retain as a percentage for each tire now in our game we don't just use a
            • 16:30 - 17:00 fixed value like this we actually use a lookup curve and so this is slightly complicated but basically what you can see here is that the x-axis you can think of as how much of the tire's velocity is in the red direction right now so zero would mean the tire is not sliding at all it's just rolling forward perfectly like it is right now and 1.0 would mean the tire is completely sliding sideways so we take that and we use that number how much is the tire sliding as a percentage of its velocity to look up
            • 17:00 - 17:30 into these curves here to decide how much traction should the tire have right now so 1.0 would mean full traction let's get rid of all the velocity in the sliding direction and what 0.0 wouldn't mean we don't care at all let it slide and you can see by the shape of the curve here that basically what we have is if the tires aren't slipping too much they have a lot of traction but once they start sliding too much they lose tons of traction and become really slippery and this is based loosely on how real tires work tires have a lot of grip at first
            • 17:30 - 18:00 because the rubber is kind of stretching and maintaining contact with the ground and then at some point they start to slide and when they start to slide of course the friction drops and so these are just two curves here i've got curves for the front tires and the back tires tuned separately to give the car the feel i'm looking for but ultimately in our game this is how we implemented the feel we wanted we used a simple curve that we could just draw and test to get the behavior we were looking for here's a look at how that is in code and you can see again we have a little setup
            • 18:00 - 18:30 here where we work out things like the velocity in the steering direction and then we decide how much grip we want to maintain and we use that to calculate an acceleration that becomes a force that we apply at the location of the tire in the direction of the red line which is the steering direction okay at this point we now have a car with suspension and also steering forces or friction forces so the tires don't like to slide sideways and so if prim gives a little push and
            • 18:30 - 19:00 hops inside you can see that we've created a soapbox derby racer we have a car with suspension and steering but no engine and no brakes all right so now we're down to the last force we need to calculate which is in this blue direction and it's comparatively simple because all we really need to do is apply some force in the blue direction and whichever direction the force is the tires are going to slowly roll in that direction so all i really need to work out is what kind of forces to apply to do things like accelerate and break the car
            • 19:00 - 19:30 a simple approach for acceleration would be when the player is pressing the accelerator we just apply a constant force in the blue direction let's say a hundred go hundred hundred hundred hundred right constant force equals constant acceleration and so the car is just gonna kind of speed up forever so we need something slightly more sophisticated and in our game we went with this simple animation curve that kind of represents the power or the torque of the car's virtual engine and basically what you can see here is the
            • 19:30 - 20:00 amount of torque or sort of forward force in this blue direction is based on this lookup curve and the curve is basically saying how fast is the car going right now if the car is at a standstill then we get 50 percent of our total power of our engine and when the car is kind of going at like mid speed here we have access to full torque and then as we approach our top speed the torque drops down and so the horizontal axis here is just how fast is the car going compared to its top speed and top speed is just a
            • 20:00 - 20:30 number that we select right so let's say the top speed of this car is 10 units per second then right now it's going at 10 units per second so we have no access to the torque but now we're going zero units per second so we have access to 50 percent of our torque and so that 50 or 100 of our torque again is just a multiplier on some number which is how strong is the engine which is just a the force value we've decided and this is roughly based on unreal engines that have less torque down at low rpms and then
            • 20:30 - 21:00 they have like a a band of their maximum torque and then the torque drops off as they sort of redline or start spinning really fast as you get up to top speed and this was enough for us to get a somewhat realistic car that behaved in a way we could easily tune and control with just one curve okay now that gets the car going but what about stopping the car well it turns out we've already solved this problem because stopping the car is the exact same thing as steering the car remember that the force in the red
            • 21:00 - 21:30 direction for steering was basically saying hey i don't want any velocity in this red direction tires don't like to slip so let's calculate a force to remove velocity in that direction well when the brakes are applied we're doing the exact same thing we want to basically remove any velocity in this rolling direction and so we do the exact same math we do for steering except in the blue direction this time to produce a braking force and you know you can do other things with this like you can put a maximum value on it and clamp it so that your brakes have some kind of maximum force they can apply to slowly bring the car
            • 21:30 - 22:00 to a stop and you can also add things like rolling friction which work very similarly which is when you're not pressing the gas we apply a light braking force in the opposite direction to slow the tires down to a stop here's a quick look at the acceleration code and you can see basically we're just working out the car's speed uh dividing it by the top speed of the car using that to look up into our power curve and then applying that force directly in the blue direction at the location for each tire there we have it we have a fulling driving car with
            • 22:00 - 22:30 suspension and steering and acceleration and braking and we can really tune this pretty easily by adjusting just a small number of values for things like the suspension and the grip and the power curve thank you for watching this video and if you'd like to support us you can definitely check out our game very very valet which is now available on nintendo switch steam and playstation 5. and of course if you like these dev style videos please give a like and consider subscribing to our channel and we'll make some more thanks again bye
            • 22:30 - 23:00 you