Game programming

My first game in Unity part4 bis – Update of the code

Update of drag
I think I made a mistake somewhere when I wrote the drag code. I don’t know what happened, it seemed it was working, but actually wasn’t. I think that OnTriggerStay2D works only ONCE, but if the collision stops and starts again, it gets messy (for example if there is another jump). Very weird (and disappointing), the engine should understand by default that the condition resets when stay isn’t true anymore (and is true again when there is contact).

After a few tries, I came to the conclusion that I needed to use OnTriggerExit2D as well, because the engine is too dumb to do the obvious. Then, by using that, the condition does become false, and the engine follows my orders. At last. Here is the revised code:

Driving behavior “improvement”
By using drag, I find it takes too long for the car to fully stop, unless using a high value (which is not what I want). I’m now using 0.1, it gives a somewhat realistic look to the deceleration, except at low speed. I wanted the car to stop moving, so I added some code that says that the motor will be active AND the motorspeed set to 0, which will immobilize the vehicle only when no keys are pressed and when the velocity of the vehicle is between -0.2 and 0.2 (in a nutshell, it forces it to stop when its speed is very low).

You’ve probably noticed the code starts with an else (instead of just an if). That’s because before that driving part, there is code for other things such as the run out of gas option. I’m not sure it’d work if I used if instead of else, but it’s working like that, so for now I’m leaving it as such. I’ll give more details about the gas stuff in another post.

I think that’s pretty much it! With that, we’re getting something “edible”…

Leave a Reply