React Pong游戏角色切换移动方向时异常弹跳问题求助
Pong游戏角色移动方向切换时出现指数级弹跳问题
我正在制作一款Pong游戏,使用W/S键控制玩家角色上下移动,但切换移动方向时,角色会出现意外的指数级弹跳现象。
最初代码
import logo from "./logo.svg"; import { useState, useEffect } from "react"; import "./App.css"; function App() { const [location, setLocation] = useState(100); document.addEventListener("keypress", (e) => handleclick(e)); const handleclick = (e) => { const key = e.key; console.log(key); if (key == "w") { setLocation((prevLocation) => prevLocation - 10); } if (key == "s") { setLocation((prevLocation) => prevLocation + 10); } }; //! problem is when you change the direction player bounce return ( <div className="App"> <div className="player1" style={{ top: location + "px", }} ></div> </div> ); } export default App;
CSS无问题,暂不考虑。
我尝试将setLocation的函数式更新改为直接使用location值更新,但问题依旧,甚至出现无限循环导致应用崩溃——状态虽能正常变更,但事件监听器内的函数会无限执行。之后我将keypress改为keydown事件,还添加了keyup事件来移除keydown监听器,问题仍未解决,修改后的代码如下:
修改后的代码
function App() { const [location, setLocation] = useState(100); document.addEventListener("keydown", (e) => handleMove(e)); document.addEventListener("keyup", () => { document.removeEventListener("keydown", (e) => handleMove(e)); }); console.log(location); const handleMove = (e) => { const key = e.key; if (key == "w") { setLocation(location - 10); } if (key == "s") { setLocation(location + 10); } }; //! problem is when you change the direction player bounce return ( <div className="App"> <div className="player1" style={{ top: location + "px", }} ></div> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者guardian
相关产品推荐
相关产品推荐

