Object Movement 2D— Controlling the Speed
How do I manipulate the movement speed of an object?
Objective: Break down some of the basic coding practices with “transform.translate” to better control a moving object’s speed.
At the end of last article we made it so that the Player (square) will move across the screen. However, the speed at which it moves is currently dependent on frame rate which can be vastly different between two computers/consoles/phones.
In Unity there is a specific code that allows us to convert anything that is currently FPS into exact seconds instead. The phrase needed is “Time.deltaTime”. Also, C# follows a lot of the same rules as we learned in school. So if you want to take the current speed (1 meter per frame) and instead multiply it times “Time.deltaTime” so that it equals 1 meter per second, it looks like this:
Now let’s talk about tweaking the speed even further. At the moment using “.right” or “.up” etc only moves it at 1 meter per second. We want to be able to increase or decrease that amount as desired. We’ve normalized it so that no matter who plays our game, the speed is the same, but it doesn’t have the “feel” we want.
If the current speed is 1 meter per second, then let’s say you want it to be 5 meters per second. Then we revert to basic math again, so “1 x 5 = 5”. That will look like this:
All we’ve done here is say “speed up on the Y axis by 1 meter per frame, times 5, times Time.deltaTime (the number of frames need to equal 1 second)”. I know that’s very wordy, but it will start to make more sense as we continue.
I know this article is much shorter than some of my others, but its the first time we’ve complicated a line of code with extras. And the next section might be long all on its own so I didn’t combine them. In the next article we’re going to discuss “variables” which will allow us to dynamically change the speed without opening our coding script!
Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9