LOVE2D,关于跟随物体的异步移动问题

我在制作一个跟随物体的小游戏,使用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
点赞
用户805875
用户805875

这段代码存在许多问题。

导致速度差异的问题是这: 如果 (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是(大约)零时的情况。)

如果您希望它朝“您”的方向移动,则跟随者应该能够在任何方向上移动。

您将不得不使用沿x和y方向的相对距离。有许多常见的距离定义选择,但您可能希望使用欧几里得距离。 (在该范数/距离定义下,“单位圆的形状”决定了它沿任何方向移动的速度有多快,只有欧几里得距离是“各个方向相同”。)

因此,将上面的块替换为

   local dx, dy = (x2-x), (y2-y)    --两个方向的差异
   local norm = 1/(dx^2+dy^2)^(1/2) --距离的长度
   dx, dy = dx*norm, dy*norm        -- x/y 部分的相对贡献
   x2, y2 = x2 - dx*speed*dt, y2 - dy*speed*dt

,您将获得“正常”的距离概念,这将使您获得“正常”移动速度概念,从而获得朝向玩家移动时相同外观的速度。

2017-07-03 15:35:27