以每秒相同的速度将div移向鼠标

时间:2018-05-29 21:30:49

标签: javascript jquery

我创建了以下代码,让玩家向鼠标移动JSFiddle

代码

var mouseX = 0, mouseY = 0;
$(document).mousemove(function(event) {
    mouseX = event.pageX;
    mouseY = event.pageY;
});

$(function(){
    var $map = $(".map");
    var $player = $('.player');

    var centerPlayerX = $player.offset().left + $player.width() / 2;
    var centerPlayerY = $player.offset().top + $player.height() / 2;

    var movingInterval;
    $('.map').on('mousedown', function(event){
            movingInterval = setInterval(function(){
            var clickedPosX = mouseX,
                clickedPosY = mouseY;

            var currentMapPositionX = parseFloat($map.css("background-position-x"));
            var currentMapPositionY = parseFloat($map.css("background-position-y"));

            var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
            var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;

            $map.css({ "background-position-x": `${moveMapX}px`, "background-position-y":  `${moveMapY}px` });

            var angle = getDirection(centerPlayerX, clickedPosY, clickedPosX, centerPlayerY);
            $player.find('.ship').css('transform', 'rotate('+angle+'deg)');
            }, 10);
    }).on('mouseup', function() {
           clearInterval(movingInterval);
        });;
});

function getDirection(x1, y1, x2, y2){
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.atan2(dx,  dy) / Math.PI * 180;
}

问题

    var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
        var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;

问题是我想以设定的速度(px * ps)移动播放器。目前,当玩家将鼠标移离图像时,玩家将加快速度。我目前不知道如何以设定的速度移动播放器。因此我需要以某种方式删除clickedPosY / X并将其更改为静态速度,但是鼠标仍然会移动图像,这就是问题所在。

1 个答案:

答案 0 :(得分:3)

所以,我们假设你有一个速度常数;你想要做的是沿着运动矢量投射速度恒定。最简单的方法是通过速度与点击点和移动基础之间距离的比率,将偏移的分量缩放到点击位置:

var distanceX = clickedPosX - centerPlayerX;
var distanceY = clickedPosY - centerPlayerY;

var magnitude = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
var deltaX = distanceX * speed / magnitude;
var deltaY = distanceY * speed / magnitude;

var moveMapX = currentMapPositionX - deltaX;
var moveMapY = currentMapPositionY - deltaY;

Updated fiddle