This is an example of how you’d move something from A to B at a linear speed. Very basic but I’m including it all…

What’s important to remember here is that this is using a time delta. If you don’t use a time delta then the ball will move at a different speed depending on the device you’re running the code on.
I’ll go into time delta in a future post but, trust me, you need to use it
Here’s the code…

Note: If you’ve been programming for a while then there’s a couple of pieces above that’ll make you twitch. Please remember that I’m writing this for clarity. We can optimise later.
What is this code doing?
The “Start” method is just setting everything up and initialising.
The “Update” is where the work is done…
m_direction is the direction we’re moving as a unit vector (a vector with a length of 1)
We multiply this unit vector by the units we want to move in one second (m_unitsPerSecond) and then we multiply by the fraction of the second used in this update (time delta)
If the distance remaining is smaller than epsilon * m_unitsPerSecond then we’re close enough to the finish point to be at the finish point
Why Epsilon?
Well, if we don’t use a ‘close enough’ for the end point then the object may never reach the end point as it could skip over it if moving fast enough.
To avoid the update always doing work, we add the epsilon so we can switch it off when it’s near enough to the end
The full Unity project can be found in github here



Leave a comment