1
I can move an element in the direction of the coordinate successfully. However, for what is needed, it must 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 faithfully), it moves all the difference in one coordinate, then in the other. Although it works, it’s still not what I need.
How can I adjust my algorithm so that I div it #viajante move 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>
<div id="drawer-wrapper">
	<div id="drawer">
	</div>
</div>
I think your solution is not working properly when the
coordenadasAlvoare less than the initial position of theviajante:(– Artur Trapp
@It is possible that if I need to help the signal
+-. I can take a closer look in a little while.– Sergio
All right, I’ll try to adjust your solution to work also for this case as exercise, meanwhile :)
– Artur Trapp
@Arturotemplário take a look now
– Sergio
Perfect! I tested so much with the
yminor with thex, and also both at the same time. It worked perfectly!– Artur Trapp