3 Answers
3

Thought Process

Rather than showing the implementation, this answer will walk you through the thought process used to design a basic 2D car without steering. Each of the headings below (behaviors, variables, and formulas) represent a portion of the thought process, and the car’s implementation.

Note: All the "code" is pseudo-code.

Behaviors

To start, we need to think about what high-level behaviors we’d like our car object to exhibit. These behaviors give insight into the methods that will need to be implemented. The key behaviors for our car are:

Starting at a defined position, with zero velocity

Adjusting velocity based on player input (accelerate and break), and modifying the car’s position

Members

The next thing we need to do is look at our behaviors and think about what pieces of information they’ll need to share with each other. These pieces of information will be our class’s member variables. The members for our car are:

It’s position (xPos, yPos)

It’s velocity (xVel, yVel)

Formulas

Finally, we use our formulas (which utilize our members), to define the behaviors we listed earlier.

You've got a velocity variable that starts at zero. As you hold the acceleration key/button, the velocity is increased by say, 2 units per frame, or whatever you want. And every frame that the velocity button isn't held, you decrement 1 unit per frame (until you get to zero). To break, decrease 2 units every frame the break button is held.

This way, you've got a car that is always slowing down while the acceleration isn't held. Of course, you can increase/decrease however much you want, based on your car's stats, the friction of the ground it's on, etc...

Now, to move the car, you look at the velocity and move it however many units you want to in the game world, based on how fast your velocity units are.