When movement changes, large jumps occur - how can you fix it?

  • 0
    Wrote an event handler for keydown that will accept a callback function.
    This function will catch pressing on the keyboard arrows. Depending on the pressed button (Up - up arrow, Left - left arrow, Right - right arrow, Down - down arrow), the square will move 10 pixels.

    BUT Big jumps of the cube occur when movement changes.
    How can you fix this?
    Sandbox
    JavaScript Everly Russell, May 14, 2020

  • 2 Answers
  • 0
    ...
    let partiesX = 0;
    let partiesY = 0;
    const moveFunc = ( event ) => {
    if ( event.code === 'ArrowUp' ) {
    partiesY -= 10;
    div.style.top = `${partiesY}px`;
    }
    if ( event.code === 'ArrowDown' ) {
    partiesY += 10;
    div.style.top = `${partiesY}px`;
    }
    if ( event.code === 'ArrowRight' ) {
    partiesX += 10;
    div.style.left = `${partiesX}px`;
    }
    if ( event.code === 'ArrowLeft' ) {
    partiesX -= 10;
    div.style.left = `${partiesX}px`;
    }

    };
    ...
    Graeme Molina

  • 0
    The number of variables storing coordinates should be adjusted to the number of axes along which the movement is carried out. And then there is one variable, but two axes. How are you going to store two independent values ​​in one variable? This is absurd - two (now attention, there will be a stunning fact) more than one.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!