Im working on a small game where a ball moves over the screen, using style.top = Math.random() and the same with style.left. However, when I specify the transition duration, at first it accelerates really quickly, and then moves to the specified place, and then really slowly slows down. I want the speed of the ball be the same throughout the whole movement.
Any ideas? Im looking for some sort of property to achieve this
2
Answers
It sounds like you’re asking about transition timing functions. Changing which function you use will change the timing curve (slow to fast, fast to slow, etc).
You’re probably going to want the
linear
function, since that has a constant rate of change.Here’s the Mozilla documentation on it: https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function
Example 1
In this example, the ball changes directions whenever it hits the border of the screen (Check the comments).
Example 2
In this example, the ball’s movement is restricted within the screen, changing direction randomly. When the ball reaches the top or bottom of the screen, the direction along the Y-axis is reversed. Similarly, when the ball reaches the left or right edge of the screen, the direction along the X-axis is reversed (Check the comments).