按esc键退出的一个函数

本文介绍了一种使用JavaScript实现当按下ESC键时关闭浏览器窗口的方法。通过监听键盘事件并检查按键代码来判断是否为ESC键,进而执行关闭操作。
1function esckey(keycode)         //按esc键退出
2        {
3            if(keycode == 27)
4                {
5                    window.close()
6                }
7        } 
你提出的需求非常合理:**按 `ESC` 退出程序运行**。 目前你的代码中虽然检测了 `WASD` 移动,但没有处理 `ESC` 退出逻辑。我们来快速、安全地加上它。 --- ### ✅ 目标: 当用户按下 **Esc **时,关闭窗口并正常退出程序。 --- ## 🔧 解决方案:在 `processInput()` 函数中添加对 `GLFW_KEY_ESCAPE` 的监听 找到你的 `processInput` 函数: ```cpp void processInput(GLFWwindow* window) { float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard('W', deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard('S', deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard('A', deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard('D', deltaTime); } ``` ### ✅ 修改为(添加 Esc 判断): ```cpp void processInput(GLFWwindow* window) { float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // WASD 摄像机移动 if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard('W', deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard('S', deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard('A', deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard('D', deltaTime); // ✅ 新增:按下 ESC 退出程序 if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); // 请求关闭窗口 } } ``` --- ## 📌 原理解释: - `glfwGetKey(window, GLFW_KEY_ESCAPE)` 检测 Esc 是否被按下。 - `glfwSetWindowShouldClose(window, true)` 会触发 `glfwWindowShouldClose(window)` 返回 `true`。 - 主循环自动结束,调用 `glfwTerminate()` 正常退出。 --- ## ✅ 效果验证: 运行程序后: - 按下 `Esc` → 窗口将在下一帧关闭 - 程序安全退出,不会崩溃或卡死 --- ## 💡 可选增强(优雅退出提示) 如果你想更“友好”,可以加一句日志: ```cpp if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { std::cout << "Exiting application...\n"; glfwSetWindowShouldClose(window, true); } ``` --- 🎯 完成后,你的交互体验将更加完整: - `WASD`:控制摄像机移动 - `鼠标`:控制视角旋转 - `Esc`:随时退出程序 --- ✅ 总结:只需在 `processInput` 中增加以下三行即可实现: ```cpp if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } ``` 现在你可以放心演示项目,任何时候都能轻松退出! 如果你还想加: - **空格暂停/继续动画** - **F1 显示帮助菜单** 请告诉我,我可以继续帮你扩展功能。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值