gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:30:25 25 4
gpt4 key购买 nike

我创建了以下代码来使玩家向鼠标移动,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 并将其更改为静态速度,但图像仍应朝着鼠标所在的方向移动,这就是问题所在。

最佳答案

所以,我们假设你有一个速度常数;你想要做的就是沿着运动矢量投影速度常数。最简单的方法是通过速度与单击点和移动底座之间的距离的比率来缩放相对于单击位置的偏移分量:

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

关于javascript - 以每秒相同的速度将 div 移向鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50593260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com