【问题标题】:Love2d move an object on screenLove2d 在屏幕上移动对象
【发布时间】:2016-05-06 13:28:41
【问题描述】:

我正在尝试使用键盘输入来翻译屏幕周围的标签。目前只有向下和向左起作用。我的代码如下。

debug = true
down = 0
up = 0
left = 0
right = 0
text = 'non'

x = 100
y = 100

dx = 0
dy = 0
function love.load(arg)

end

function love.update(dt)
    if love.keyboard.isDown('escape') then
        love.event.push('quit')
    end

    if up == 1 then
        dy = -1
    end
    if up == 0 then
        dy = 0
    end

    if down == 1 then
        dy = 1
    end
    if down == 0 then
        dy = 0
    end

    if right == 1 then
        dx = 1
    end
    if right == 0 then
        dx = 0
    end

    if left == 1 then
        dx = -1
    end
    if left == 0 then
        dx = 0
    end
end

function love.keypressed(key)
  if key == 'up' or key == 'w' then
      text = 'up'
            up = 1
  end
    if key == 'down' or key == 's' then
      text = 'down'
            down = 1
  end
    if key == 'right' or key == 'd' then
      text = 'right'
            right = 1
  end
    if key == 'left' or key == 'a' then
      text = 'left'
            left = 1
  end
end

function love.keyreleased(key)
    text = 'non'

    if key == 'up' or key == 'w' then
        up = 0
    end
    if key == 'down' or key == 's' then
        down = 0
    end
    if key == 'right' or key == 'd' then
        right = 0
    end
    if key == 'left' or key == 'a' then
        left = 0
    end
end

function love.draw(dt)
    x = x + dx
    y = y + dy
    love.graphics.print(text, x, y)
end

实验表明,love.update(dt) 部分中 if 语句的顺序会影响哪些方向有效,但我无法让所有四个同时工作。

【问题讨论】:

  • 您根据两种可能性检查每个值,然后为每个值设置一个共享值。遵循love.update 中的逻辑,在您的脑海中跟踪任何给定按键的dydx。 (请记住,您可能只更改一个值,但所有变量都有值。)

标签: lua love2d


【解决方案1】:

把 love.update 和 love.draw 改成这样:

function love.update(dt)
    if love.keyboard.isDown('escape') then
        love.event.push('quit')
    end

    dx, dy = 0

    if up == 1 then
        dy = -1
    end

    if down == 1 then
        dy = 1
    end

    if right == 1 then
        dx = 1
    end

    if left == 1 then
        dx = -1
    end

   x = x + dx
   y = y + dy
end

function love.draw(dt)
    love.graphics.print(text, x, y)
end

当您检查输入时,如果确实按下了按钮,则您会正确地为它们分配值,但您还要检查按钮是否未按下然后取消分配值。因此,如果按下了向上,则未按下向下的检查会立即覆盖分配的值。此外,您可能希望根据目标 fps 按 dt 值缩放 dx 和 dy(如果您不使用固定时间步长,即无论机器的 FPS 如何,都可以使移动速度相同)。

【讨论】:

  • 解释为什么会非常有助于使这个更好的答案。
  • 当他检查输入时,如果按钮被按下,他会正确地为它们分配值,但他也会检查按钮是否未被按下,然后取消分配值。因此,如果按下了向上,则未按下向下的检查会立即覆盖分配的值。
  • 是的,我理解这个问题,但 OP 显然没有。因此,仅仅修复代码而不解释它并不能帮助他们理解他们的逻辑错误。更新有帮助。
猜你喜欢
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多