I can move an element in the direction of the coordinate successfully. However, for what I need, it needs to move in a straight line (which is the shortest possible distance between two points).
In the example I gave below (which represents the current functionality of my code with fidelity), it moves all the difference in one coordinate, then the other. Although it works, it's still not what I need.
How can I adjust my algorithm so that the #viajante
div moves in a straight line towards coordenadasAlvo
?
var viajante = {};
var parametros = {
coordenadasAlvo : { x : 50, y : 200 },
tempoSetInterval : 100,
velocidadeViajante : 1 // pixels por tempoSetInterval (milissec)
};
$(document).ready(function (){
inicializaDrawer();
setInterval(moveViajante, parametros.tempoSetInterval);
});
function inicializaDrawer(){
viajante = $('<div id="viajante"></div>');
$('#drawer-wrapper').append(viajante);
}
function getDeslocamentoViajante(startCoord, targetCoord, speed){
var diff = startCoord - targetCoord;
return diff > 0 ? -speed : speed;
}
function getPosicaoViajante(){
var left = viajante.position().left;
var top = viajante.position().top;
return { x : left, y : top };
}
function moveViajante(){
var entityPos = getPosicaoViajante();
var diffX = getDeslocamentoViajante(entityPos.x, parametros.coordenadasAlvo.x, parametros.velocidadeViajante);
var diffY = getDeslocamentoViajante(entityPos.y, parametros.coordenadasAlvo.y, parametros.velocidadeViajante);
var newX = entityPos.x + diffX;
var newY = entityPos.y + diffY;
viajante.css({top: newY, left: newX, position:'absolute'});
}
#drawer-wrapper{
height: 300px;
width: 300px;
overflow: auto;
border: 1px solid black;
position: relative;
}
#drawer{
height: 300px;
width: 300px;
background-color: green;
}
#viajante{
width: 20px;
height: 20px;
background-color: red;
position: absolute;
top: 0;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="drawer-wrapper">
<div id="drawer">
</div>
</div>