You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LÖVE2D中love.keyboard.isDown未触发,按a/d键无法控制挡板移动

问题原因

  • 核心错误:LÖVE2D 引擎的帧更新回调函数必须命名为 love.update(dt),你当前代码中定义的是普通函数 update(dt),引擎不会主动调用该函数,按键判断和坐标修改逻辑从来没有执行,所以挡板没有反应。
  • 额外可优化点:没有加边界判断,持续按键会导致挡板移出窗口可视区域。

修复方案

把更新函数的函数名改成 love.update,同时可选添加边界限制逻辑,修正后的完整代码如下:

window_width = 580
window_height = 420

playerScore = 0
enemyScore = 0

pSpeed = 200

player1Y = 100
player2Y = -20

function love.load()
  love.window.setMode(window_width, window_height)
end

function love.draw()
  love.graphics.printf('hello pong', 0, window_height / 2 - 6, window_width, 'center')
  -- 右侧玩家挡板
  love.graphics.rectangle("fill", 500, player1Y , 10, 50)
  -- 左侧固定挡板
  love.graphics.rectangle("fill", 40, 220, 10, 50)
  love.graphics.rectangle("fill", 100, 230, 7, 5)
end

-- 修正函数名,改为love.update
function love.update(dt)
  if love.keyboard.isDown('d') then                     
    player1Y = player1Y + pSpeed * dt
  elseif love.keyboard.isDown('a') then               
    player1Y = player1Y - pSpeed * dt
  end
  -- 可选添加边界限制,防止挡板移出屏幕
  if player1Y < 0 then
    player1Y = 0
  end
  if player1Y > window_height - 50 then -- 50是挡板高度
    player1Y = window_height - 50
  end
end

内容的提问来源于stack exchange,提问作者cleo the puppy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 20:24:01