Moving an object along a straight line at a constant speed from point A to B

后端 未结 2 1047
清酒与你
清酒与你 2020-12-10 19:01

I know this has been asked a few times before, but there has been no answer that actually works that I can find. There is a similar one, but the speed varies dependi

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 19:51

    Your problem seems to be that xRatio and yRatio are angles, not vector coordinates. This should work:

    document.addEventListener('mouseup', function(e) {
        movePlayer(selectedPlayer, {x:e.pageX, y:e.pageY});
    });
    
    function movePlayer(player, target) {
        var start = {
                x: player.x,
                y: player.y,
                t: Date.now()
            },
            distance = Math.sqrt(distance.x*distance.x + distance.y*distance.y),
            time = distance; //This may seem pointless, but I will add a speed variable later
            difference = {
                x: target.x - player.x,
                y: target.y - player.y,
                t: time
            };
    
        player.angle = Math.atan2(distance.y, distance.x) * (180 / Math.PI);
    
        //This function is called in another part of code that repeats it 60 times a second
        walkPlayer = function(curTime) { // we need timing information here: Date.now()
            var elapsed = curTime - start.t,
                ratio = elapsed / difference.t;
            player.x = start.x + difference.x * ratio;
            player.y = start.y + difference.y * ratio;
            if (ratio >= 1) {
                player.x = target.x;
                player.y = target.y;
                // end calling of walkPlayer
            }
        };
    }
    

提交回复
热议问题