LOVE2D,跟随者对象的异步运动

时间:2017-07-03 12:44:39

标签: lua synchronization game-physics 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

1 个答案:

答案 0 :(得分:0)

   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(大约)为零时的情况。)

如果您希望它“直接朝向您”移动,则关注者应该能够向任何方向移动。

您必须使用沿x和y方向的相对距离。有many common choices of distance definitions,但您可能需要euclidean distance。 (该范数/距离定义下的"shape" of the unit circle确定它在任一方向上移动的速度,只有欧几里德距离“在所有方向上都相同”。)

所以用

替换上面的块
   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

你将获得距离的“正常”概念,它可以让你获得正常的移动速度概念,这可以让你在向玩家移动时获得相同的速度。