There is a simple example: codepen.io/anon/pen/WxONkk

Clicking on the grass you can see that the red square does not move consistently, but by teleports.

I found the following demo on the Internet: http://www.briangrinstead.com/files/astar-original/

And in the demo everything works as it should, but is it possible to apply the technology that is in the demo to my example?

In the canvas example, I have the usual div. Thanks for any help.

  • one
    instead of instantaneous movement to the specified coordinate - split the movement to the coordinate into horizontal and vertical movement ..... and then simply animate this transition along one axis and then along the other ... in N steps ... leave a clone of a square at each step that destroys in M milliseconds - Alexey Shimansky
  • @ Alexey Shimansky Please post your comment as a response. - Nicolas Chabanovsky
  • Try the tweenjs library github.com/tweenjs/tween.js - iKest

1 answer 1

It is necessary to keep the current coordinates of the cube, and the coordinates of the target. While the cube to the goal is where to move, the timer works, which moves the cube 1 time at a time: horizontally or vertically. If you need to move obliquely, he randomly chooses either a horizontal or vertical move. To smooth the movement, use the CSS3 transition property:

 var tile = { w: 32, h: 32 }, map = { w: 29, h: 24 }, x, y, div, i = 0, cube = { x: 0, y: 0, el: document.getElementById('cube') }; for (y = 0; y <= map.h; y++) { for (x = 0; x <= map.w; x++) { div = document.createElement('div'); div.setAttribute('id', 'tile_' + x + '_' + y + '_0'); div.setAttribute('class', 'tile'); div.setAttribute('style', 'top: ' + (y * tile.h) + 'px; left: ' + (x * tile.w) + 'px;'); map001.appendChild(div); } } var target = { x: 0, y: 0 }, timer; document.body.addEventListener('click', function(e) { if (e.target.classList.contains('tile')) { move(e.target); } }); function move(tile) { var id = tile.id.split('_'); target.x = parseInt(id[1]); target.y = parseInt(id[2]); if (!timer) timer = window.setInterval(step, 100); } function step() { var dx = Math.sign(target.x - cube.x), dy = Math.sign(target.y - cube.y); if (!dx && !dy) { window.clearInterval(timer); timer = undefined; return; } if (dx && dy) { if (Math.random() > 0.5) { dx = 0; } else { dy = 0; } } cube.x += dx; cube.y += dy; cube.el.style.transform = 'translate(' + (cube.x * tile.w) + 'px,' + (cube.y * tile.h) + 'px)'; } 
 * { margin: 0; padding: 0; } #map001 { width: 960px; height: 800px; } #map001 div { background: url(http://store.picbg.net/pubpic/BD/F6/d86cd1eb00f1bdf6.png); z-index: 0; } #cube { background: #939; z-index: 1; transition: transform 0.15s; } #map001 div, #cube { width: 32px; height: 32px; position: absolute; } 
 <div id='cube'></div> <div id='map001'></div>