Let’s first take a look at the previous uniform motion code and see what kind of bug will occur after modifying the speed. Two benchmarks are added here for testing
Then why does this happen?
In fact, when he reaches the target point, he cannot accurately reach the target point. If the target point is 100, and he walks 7 times each time, he will either pass the target point at this time, or he will not pass it.Never reach the target point. In fact, it is a bit similar to the previous buffer.
So how do you calculate that you have reached the target point?
For example: When you take a taxi to a certain place, the driver must have stopped about 10 or 20 meters away from where you are, then you have arrived. It's impossible to ask the car to stop at that place.
So, in fact, the procedure is the same. As long as the distance between the object and the target point is close to a certain level, there is no need to get closer, and we think it is done.
Let’s take a look at the modified code:
time = setInterval(function() {
var speed = 0;
If (oDiv.offsetLeft < iTarget) {
Speed = 7;
} else {
Speed = -7;
}
If (Math.abs(iTarget - oDiv.offsetLeft) <= 7) {
oDiv.style.left=iTarget 'px';
} else {
oDiv.style.left = oDiv.offsetLeft speed 'px';
}
}, 30)
}
Explain: Why do we use Math.abs to get the absolute value here?
The reason is simple, because the speed may be positive or negative.
Now we let the distance between the target and the object be less than 7, that’s it. Why is it 7? Because his next exercise will be less than 7. At this time we will count him as reaching the target point.
Then the problem comes again. Writing like this, he did not stop exactly at the target point. So we added a simple sentence and directly made left equal to the target point. oDiv.style.left=iTarget 'px';
In fact, less than 7 people left last time, but everyone knows that the program runs too fast and cannot be seen by the human eye. Warm smile
There will be no problem at this time. wink
This is the stopping condition for uniform motion. Then some friends asked, why is buffering exercise not so troublesome?
Because his speed is changing, getting smaller and smaller, until in the end he even reaches 1. If you move forward step by step, there will definitely be no such problem.