JavaScript movement (acceleration movement, elastic movement)

Accelerated motion (acceleration constant acceleration)

function addSpeed(dom){
            var a = 5;
            timer = setInterval(function(){
                speed =  speed + a;
                dom.style.left = dom.offsetLeft + speed + 'px';
            },30)
        }

 

Elastic sports

When a spring link elastic ball movement

  1. (Nail on the left), ball movement direction to the right, subject to the right of force, acceleration right, do reduce the acceleration of accelerated motion
  2. When the right (nail right side), the direction of movement of the ball to the right, the force received by the left, the left acceleration, deceleration acceleration increases do
  3. When the left (right nail), the direction of ball movement to the left, the force received leftward, leftward acceleration, motion acceleration accelerated and a reduced
  4. When the left (the left side of the nail), the direction of ball movement leftward, rightward force received rightward acceleration, deceleration motion acceleration increases made

That is when the ball farther from the nail (the target location), subject to the greater acceleration, decreasing with distance, acceleration is also decreasing. When implementing code to control the magnitude of the acceleration is determined by the distance of the object from the target point, which means that we can use a = target - dom.offsetleft; since the case can be divided by the acceleration is too large a number.

function moveStart(dom, targetPosition) {
            clearInterval(timer);
            var speed = 0; var a = 3 ;
            timer = setInterval(function () {
                a = (targetPosition - dom.offsetLeft) / 5;
                speed = speed + a;
                speed = speed * 0.8;if (Math.abs(speed) < 1 && Math.abs(targetPosition - dom.offsetLeft) <= 1) {
                    clearInterval(timer);
                    dom.style.left = targetPosition + "px";
                } else {
                    dom.style.left = dom.offsetLeft + speed + "px";
                }
            }, 30)
        }

 

 

 

 

In the true green elastic movement, due to friction and air resistance, the speed is energy loss. We let the body such as the role of friction in speed: speed * u; when the speed is reduced to zero and the distance to the target position is less than 1, the timer is stopped.

 

 

 

Guess you like

Origin www.cnblogs.com/jiaobaba/p/11488334.html