I'm not good in math so I'm here to ask you how to manage, in a simple 2d game, the car acceleration and braking.
I'm trying to develop it (as a hobby) in c# and sdl.net.
I'm not good in math so I'm here to ask you how to manage, in a simple 2d game, the car acceleration and braking.
I'm trying to develop it (as a hobby) in c# and sdl.net.
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.
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:
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:
Finally, we use our formulas (which utilize our members), to define the behaviors we listed earlier.
Start at a defined position, with zero velocity
(xPos, yPos) = (starX, startY)
(xVel, yVel) = (0,0)
Adjust velocity based on player input
// acceleratedX/Y represents the acceleration/deceleration amount
(xVel, yVel) += (acceleratedX, acceleratedY)
Simulate drag to slow the car down
(xVel, yVel) -= (drag,drag)
Make sure we don't go in reverse!
if (xVel < 0) { xVel = 0 }
if (yVel < 0) { yVel = 0 }
And our car should work! :D
To get you thinking, here is how you might consider it:
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.
There's a really good article on just this, 2D car physics at gamedev.net and its based on C#.