How to control acceleration and acceleration in my game in C #

I build driving. The look is promising, and the playerโ€™s perspective is due to the machine that is moving forward. When the car moves forward, its entire environment moves down and scales (now it looks good), which gives the impression that the car is moving forward. Now I want to have some realistic controls for the car to increase speed and then slow down slowly when the up arrow is released. Currently, I call all the move functions for multiple sprites when I press the up arrow. I am looking for a way to control this, so functions are not called so often when the machine is slow, etc. Etc. The code I have so far is:

protected void Drive() { KeyboardState keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Up)) { MathHelper.Clamp(++TruckSpeed, 0, 100); } else { MathHelper.Clamp(--TruckSpeed, 0, 100); } // Instead of using the condition below, I want to use the TruckSpeed // variable some way to control the rate at which these are called // so I can give the impression of acceleration and de-acceleration. if (keyState.IsKeyDown(Keys.Up)) { // Lots of update calls in here } } 

I thought this should be easy, but for some reason I cannot understand. It would be very helpful to help here! Thanks

+6
source share
3 answers

First sentence, do not use ++ and -- . Increase the pace of TruckSpeed at a speed times Delta Time . This means that your acceleration and deceleration will work the same on slower and faster computers and will be independent of hickup. You may also have different increases and decreases in order to better control your gameplay.

Something along the lines of:

 protected void Drive(GameTime gameTime) // Pass your game time { KeyboardState keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Up)) { TruckSpeed += AccelerationRatePerSecond * gameTime.ElapsedGameTime.TotalSeconds; } else { TruckSpeed -= DecelerationRatePerSecond * gameTime.ElapsedGameTime.TotalSeconds; } MathHelper.Clamp(TruckSpeed, 0, 100); ... 

Alternatively, you can probably replace

 if (keyState.IsKeyDown(Keys.Up)) 

by

 if (TruckSpeed > 0) 

It's probably easier to attach a camera to your model and move it to the environment, instead of moving the entire environment around the truck, though ...

+4
source

The easiest and most correct approach is to separate keyboard control from physics. You want the acceleration to be measured when / in units of time, not to change / at the press of a button. Than in each iteration you need to change the speed depending on the time elapsed since the last update ...

0
source

Acceleration is not linear. Therefore, I would recommend not using ++ or - operators. Instead, call a function that calculates the change in speed over time (delta V) / time. If you need a true sense of acceleration, you can think of something in this regard.

0
source

All Articles