Home > database >  How to css animate per pixel distance, or consistent speed
How to css animate per pixel distance, or consistent speed

Time:03-11

var field = document.getElementById('field');
var player = document.getElementById('player');
field.oncontextmenu = (e) => {
    var xposition = (e.clientX - player.offsetLeft - player.offsetWidth/2);
    var yposition = (e.clientY - player.offsetTop - player.offsetHeight/2);
    player.style.transform = "translate("  xposition   "px,"   yposition   "px)";
    e.preventDefault();
}
#field{
    width: 500px;
    height: 500px;
    background-color: #999;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #player{
    background-color: #f30f4f;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    transform-origin: 25px 25px; 
    transition: all 0.3s linear;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="layout.css">
    <title>TESTING</title>
</head>
<body>
    <p> Right click in the grey box </p>
    <div id="field"></div>
    <div id="player"></div>
    <script src="layout.js"></script> 

</body>
</html>

Instead of transition: all 0.3s linear; is there a way to make it move f.e. 2px per 0.3s? Right now if the player moves a longer distance it moves faster than moving a short distance (since it has to move further in 0.3s): I would want that to be the same consistent speed.

CodePudding user response:

You need to calculate distance between current and target positions and divide it by the desired speed to get the duration of the movement:

var field = document.getElementById('field');
var player = document.getElementById('player');
var position_current = {x: -25, y: -25}; // current position
var speed = 200; // pixels per second
field.oncontextmenu = (e) => {
    var position_new = {
        x: (e.clientX - player.offsetLeft - player.offsetWidth/2),
        y: (e.clientY - player.offsetTop - player.offsetHeight/2)
    }

    var distance = Math.hypot(
        position_new.x - position_current.x,
        position_new.y - position_current.y,
    );
    
    player.style.transitionDuration = (distance/speed)   's';
    player.style.transform = "translate("  position_new.x   "px,"   position_new.y   "px)";

    position_current = position_new;
    e.preventDefault();
}
  • Related