LOVE2D,跟随对象的去同步运动

LOVE2D, Desync movement of follower-object

我的代码有问题。 (Love2D框架) 我正在制作小型随动对象,它会实时跟随坐标。 问题是运动速度在变化,这取决于矢量。 就像向前移动比向左上移动稍微快一点。 有人可以帮我吗?请标记我的错误。 代码:

    function love.load()
    player = love.graphics.newImage("player.png")
    local f = love.graphics.newFont(20)
    love.graphics.setFont(f)
    love.graphics.setBackgroundColor(75,75,75)
    x = 100
    y = 100
    x2 = 600
    y2 = 600
    speed = 300
    speed2 = 100
end

function love.draw()
    love.graphics.draw(player, x, y)
    love.graphics.draw(player, x2, y2)
end

function love.update(dt)
print(x, y, x2, y2)
   if love.keyboard.isDown("right") then
      x = x + (speed * dt)
   end
   if love.keyboard.isDown("left") then
      x = x - (speed * dt)
   end

   if love.keyboard.isDown("down") then
      y = y + (speed * dt)
   end
   if love.keyboard.isDown("up") then
      y = y - (speed * dt)
   end

   if x < x2 and y < y2 then
    x2 = x2 - (speed2 * dt)
    y2 = y2 - (speed2 * dt)
   end

   if x > x2 and y < y2 then
    x2 = x2 + (speed2 * dt)
    y2 = y2 - (speed2 * dt)
   end

   if x > x2 and y > y2 then
    x2 = x2 + (speed2 * dt)
    y2 = y2 + (speed2 * dt)
   end

   if x < x2 and y > y2 then
    x2 = x2 - (speed2 * dt)
    y2 = y2 + (speed2 * dt)
   end
end

这个

   if x < x2 and y < y2 then
    x2 = x2 - (speed2 * dt)
    y2 = y2 - (speed2 * dt)
   end

   if x > x2 and y < y2 then
    x2 = x2 + (speed2 * dt)
    y2 = y2 - (speed2 * dt)
   end

   if x > x2 and y > y2 then
    x2 = x2 + (speed2 * dt)
    y2 = y2 + (speed2 * dt)
   end

   if x < x2 and y > y2 then
    x2 = x2 - (speed2 * dt)
    y2 = y2 + (speed2 * dt)
   end

有一堆问题。

造成速度差异的原因是:如果 (x<x2),但 x>(x2+speed2*dt),您将 运行 通过第一个分支 (if x < x2 and y < y2 then …)。这将更改值,以便您也将点击第二个分支 (if x > x2 and y < y2 then …),这意味着您在 y 方向上移动了两次。更改为 if x < x2 and y < y2 then … elseif x > x2 and y < y2 then … 这样您就不会掉入其他分支,或者进行数学运算并避开整个 if 链。

一件你可能想要也可能不想要但目前拥有的东西是它要么朝某个方向走,要么不走。这意味着随从可以行驶 8 个可能的方向。 (轴对齐或对角线 - 您拥有的 4 种情况加上 dx 或 dy 为(近似)零的情况。)

如果你想让它移动"directly towards you",随从应该可以向任何方向移动。

您将不得不使用沿 x 和 y 方向的相对距离。在该范数/距离定义下有 many common choices of distance definitions, but you probably want the euclidean distance. (The "shape" of the unit circle 决定了它在任一方向移动的速度,只有欧氏距离是 "the same in all directions"。)

所以将上面的块替换为

   local dx, dy = (x2-x), (y2-y)    -- difference in both directions
   local norm = 1/(dx^2+dy^2)^(1/2) -- length of the distance
   dx, dy = dx*norm, dy*norm        -- relative contributions of x/y parts
   x2, y2 = x2 - dx*speed*dt, y2 - dy*speed*dt

你会得到 "normal" 距离的概念,这让你得到了正常的移动速度概念,这让你在向玩家移动时看起来速度相同。